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