Quiz
Warm-up from lesson 3-2: bio?: string made an object property optional. What do you expect title? to mean in function greet(name: string, title?: string)?
Parameters callers may skip
In JavaScript every parameter was silently optional, missing ones just became undefined. TypeScript flips that: parameters are required unless you say otherwise.
function greet(name: string, title?: string): string
title? allows the two-argument and one-argument calls, and inside the body title has type string | undefined, the union from Unit 4. Narrow it with a check before use.
A default parameter goes one step further and supplies the fallback value itself:
function ticketPrice(age: number, discount: number = 0): number
With a default, the parameter is optional for callers but never undefined inside the body, so no check is needed. Optional parameters must come after required ones.
Code exercise · typescript
Run it, then try calling greet() with no arguments to see that name is still required.
Code exercise · typescript
Your turn. Write ticketPrice(age: number, discount: number = 0): number. The base price is 5 when age < 12, otherwise 12. Return base minus discount. Print ticketPrice(30) and ticketPrice(8, 2).
Rest parameters: any number of arguments
console.log happily takes one argument or five. Your own functions can too. A rest parameter collects every remaining argument into an array — declare it with ... and give it an array type:
function sum(...nums: number[]): number
Callers write sum(1, 2, 3) or sum(); inside the body, nums is an ordinary number[] you can loop over. Two rules follow from what it is: a rest parameter must come last (it absorbs everything after it), and its type must be an array type, because an array is what the collected arguments become. The payoff is that variable-argument functions stay fully checked — sum(1, "2") is a compile error, not a NaN at runtime.
Code exercise · typescript
Your turn. Write sum(...nums: number[]): number that adds every argument with a for..of loop and returns the total. Print sum(1, 2, 3), sum(10, 20), and sum().