typescript · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A function works for any type, and remembers which.
Picture a function that gives back the first item of an array. Write it for string[] and it is no use for numbers. Write a copy for each type and you repeat yourself. A generic function solves this with a .
A type parameter is a placeholder for a type, written in angle brackets after the name: function first<T>(items: T[]): T. Read T as “some type”. Each call fills it in: pass a number[] and T becomes number, so you get a number back.
You rarely need to say which type. The checker works it out from the arguments.
function first<T>(items: T[]): T {
return items[0];
}
const top = first([42, 17, 8]);
const winner = first(["Ava", "Ben"]);
console.log(top + 1);
console.log(winner.toUpperCase()); T is a habit, short for type. Any name works, like Item.
guess first
The checker remembers the type. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function last<T>(items: T[]): T {
return items[items.length - 1];
}
const word = last(["red", "amber", "green"]);
console.log(word.length);
const num = last([3, 6, 9]);
console.log(num.length);
your turn
Your turn. Write a generic pair maker.
Fill in the type of the second parameter so both must match, then make one pair of numbers and one pair of strings.
fix it
The gift wrapper forgot its type. Fix it!
- Read the error:
TS2304: Cannot find name 'T'.The checker does not know whatTis. - A type parameter must be introduced in angle brackets, straight after the function's name.
- Change line 1 to
function wrap<T>(value: T): T[] {then press run.
nailed it
your functions work for every type. :D
- A generic function has a type parameter, like
<T>. - Each call fills in
Tfrom its arguments. - The checker remembers the type, so the answer stays typed.
new words in your collection
- generic
- type parameter
This lesson isn’t saved. A free account remembers every lesson you finish.