typescript · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Parameters can be optional, or come with a .
Until now every parameter needed an argument, or the checker said TS2554. Put ? after a parameter's name, like role?: string, and it becomes an . Leave it out of the call and it is undefined inside.
Often you want a sensible fallback instead. Give the parameter a default value with =, like greeting: string = "Hello". If the call leaves it out, the default is used. If the call passes one, that wins.
Optional and default parameters go after the required ones, so the checker knows which argument is which.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
function badge(name: string, role?: string): string {
return `${name} (${role ?? "guest"})`;
}
console.log(greet("Mo"));
console.log(greet("Mo", "Welcome back"));
console.log(badge("Ivy", "host"));
console.log(badge("Sid")); A default value also tells the checker the type, so greeting = "Hello" would be a string anyway.
guess first
Defaults and overrides. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function brew(drink: string, sugars: number = 0, milk: boolean = true): string {
return `${drink}, ${sugars} sugar, milk: ${milk}`;
}
console.log(brew("tea", 2));
console.log(brew("coffee", 0, false));
your turn
Your turn. Order pizza with a default size.
Give size a default value. Then order one pizza with a topping and a size of your own, and one with only a topping, so it uses the default.
fix it
The optional slot jumped the queue. Fix it!
- Read the error:
TS1016: A required parameter cannot follow an optional parameter. - Optional parameters must come after the required ones. Swap the two parameters, and then the two arguments too.
- Make line 1
function sign(text: string, colour?: string): string {and line 4console.log(sign("SALE", "red"));then run.
nailed it
your functions have sensible defaults. :D
- A
?after a parameter lets a call leave it out. = valuegives a parameter a default value.- Optional and default parameters go after the required ones.
new words in your collection
- optional parameter
- default value
This lesson isn’t saved. A free account remembers every lesson you finish.