Generic Functions
Generic Functions
π¨βπΌ We have utility functions that work with arrays, but they're limited to
specific types. Let's make them generic so they work with any type.
The syntax for generic functions:
function functionName<Value>(param: Value): Value {
return param
}
The
<Value> declares a type parameter. When you call the function,
TypeScript infers (or you specify) what Value is:identity<string>('hello') // Explicit: Value is string
identity(42) // Inferred: Value is number
π¨ Open
and:
- Create a generic
identityfunction that takes a value and returns the same value (preserving its type) - Create a generic
lastfunction that takes anArray<Item>and returnsItem | undefined(the last element, orundefinedfor an empty array) - Export
identityandlastby name
Completion criteria
- Named exports:
identity,last identityreturns the same value for strings, numbers, booleans, andnulllast([1, 2, 3])β3;last(['a', 'b', 'c'])β'c';last([])βundefined
π° Use a type parameter to make the array function work with any type.