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 returns its input - Create a generic
lastfunction that returns the last array element
π° Use a type parameter to make the array function work with any type.