Lesson 1 of 10
Generics
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
The return type follows the input type
Explanation
Say you have a function that returns the first element of an array. What type does it return? If you write any, you lose everything types give you, because the compiler no longer knows that the first element of a string[] is a string.
Generics make the type itself a parameter you pass to the function, like this: function first<T>(xs: T[]): T | undefined. Pass an array of strings and T automatically becomes string. Pass numbers and it becomes number.
The | undefined isn't there for decoration. An empty array has no first element, and this type makes whoever calls the function deal with that case.
Your task
Make first a generic function, so the type it returns follows the type of the array you pass it.
Checks
6 checks- No type errors
- Returns the first element
- An empty array returns undefined
- With an array of strings, the result is a string
- The result isn't treated as a number
- The result may be undefined, so it can't be assigned to a plain string