Generics
Without generics, a "return the first element" function would need typing
per array type: one for number[], another for string[]. A generic
function instead declares a placeholder type name - conventionally T -
right after its own name, then uses T anywhere a real type would go:
function first<T>(arr: T[]): T {
return arr[0];
}
T isn't a real type - it's filled in per call. first([10, 20, 30]) fills
T with number; first(["a", "b"]) fills it with string. The body never
needs to know which - arr[0] works identically either way.
Your task: write first(arr) so it returns the first element of any
array, typed generically.
You'll practice:
Declaring a generic type parameter with <T>
Using T in a parameter and return type
Show a hint
Show solution
Related reading: Generics - Reusable Code That Keeps Its Types →
Previous Next