×

typescript · level 2 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.