optional/default parameters

  • optional parameter x?: T is of type T | undefined.

  • default parameter x = value is of type T (suppose value is of type T).

const { log } = console;

// ⭐️ optional parameters
//   --------------------
// ⭐️ `x` is of type `number | undefined` ❗️
//    (similar to Optionals in Swift)
function f(x?: number) {
  log( x ?? 0 );
}

f();        // 0
f(10);      // 10

// ⭐️ default parameters
//   -------------------
// ⭐️ `x` is of type `number`
function g(x = 4){
  log(x);
}

g();          // 4
g(5);         // 5
g(undefined); // 4 === g()

Last updated