Generic helpers
- TypeScript course
- Intermediate
- Lesson 73/89
- 5 min
Add generic helper functions.
Generic helper functions
Generic helper functions are reusable tools that work with any type. The type parameter is specified with <T>, making the function both type-safe and flexible. In a library, helpers like identity, first element, and filtering are typically written as generics.
function identity<T>(x: T): T {
return x;
}Common helpers
Common generic helpers include first (first array element), pick (select fields from an object), and groupBy (grouping). These functions form the core toolkit of the library and are used repeatedly in application code.
function first<T>(arr: T[]): T | undefined {
return arr[0];
}Practice firstElement generic helper
Define a generic function named firstElement: <T>(arr: T[]): T | undefined. Its body should be return arr[0]. Print the result of calling firstElement(["a", "b"]) with console.log.
Starter code
// firstElement adında generic fonksiyon tanımla
// dizi ilk elemanını dönsün
// ["a", "b"] ile çağırıp yazdırSample solution
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
console.log(firstElement(["a", "b"]));Expected output
a
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the advantage of a generic helper function?
- Eliminates the need to specify types
- Works only with numbers
- Works with any type while preserving type safety Correct answer
- Runs faster at runtime
Explanation: Generic functions work with any type via the <T> type parameter, but the compiler preserves type safety.
2 First element index
function first<T>(arr: T[]): T | undefined {
return arr[____];
}
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
Explanation: The first element of an array is at index 0; it is accessed via arr[0].
3 Generic helper concepts
| Term | Meaning |
|---|---|
<T> |
Type parameter |
identity |
Returns what it takes |
first |
First array element |
T | undefined |
Maybe absent |