typescript · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Take any number of arguments with a .
Some functions should accept as many arguments as you like: total(2, 5) or total(2, 5, 9, 1). Put three dots before the last parameter, ...prices: number[], and it becomes a rest parameter: an array holding every leftover argument.
Three dots also work the other way. In a call, total(...basket) is a : it unpacks an array into separate arguments. If a function wants exactly two arguments, the checker needs a tuple, like [number, number], to know the count fits.
function total(...prices: number[]): number {
let sum = 0;
for (const price of prices) {
sum = sum + price;
}
return sum;
}
console.log(total(2, 5));
console.log(total(2, 5, 9, 1));
const basket: number[] = [3, 4, 3];
console.log(total(...basket)); A rest parameter always comes last, because it takes everything that is left.
guess first
Spread a room into a sum. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function area(width: number, height: number): number {
return width * height;
}
const room = [4, 3];
console.log(area(...room));
your turn
Your turn. Host a party for any number of guests.
Write the rest parameter so partyList takes a host and any number of guests, then invite at least two guests.
fix it
The invitations will not send. Can you fix them?
- Read the error:
TS1014is about where a rest parameter is allowed to go. - A rest parameter takes every argument that is left, so nothing can come after it.
- Put
party: stringfirst and...friends: string[]last, then pass the party name first in the call.
nailed it
your functions take as many as you like. :D
...prices: number[]collects every leftover argument into an array.- A rest parameter always comes last.
- Spread a tuple, like
[number, number], into fixed parameters.
new words in your collection
- rest parameter
- spread
This lesson isn’t saved. A free account remembers every lesson you finish.