๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

TypeScript Optional and Default Parameters

An optional parameter may be left out at a call. A default parameter supplies a value when its argument is left out.

An optional parameter

The greeting may be left out. Inside the function, an omitted parameter holds undefined.

function greet(name: string, greeting?: string): string {
  if (greeting === undefined) {
    return "Hello, " + name;
  }
  return greeting + ", " + name;
}
console.log(greet("Ada"));
console.log(greet("Ada", "Welcome"));

A default parameter

The tax rate defaults to 0.1. A call may pass its own rate instead.

function total(price: number, taxRate: number = 0.1): number {
  return price + price * taxRate;
}
console.log(total(100));
console.log(total(100, 0.25));

One argument too many is refused

The function takes one parameter. A call with two arguments fails the check.

function greet(name: string): string {
  return "Hello, " + name;
}
console.log(greet("Ada", "Ben"));

Example

function receipt(item: string, quantity: number = 1, note?: string): string {
  let line: string = item + " x" + quantity;
  if (note !== undefined) {
    line = line + " (" + note + ")";
  }
  return line;
}
console.log(receipt("Notebook"));
console.log(receipt("Pen", 3));
console.log(receipt("Mug", 2, "gift"));

Key points

  • A question mark after a parameter name makes that parameter optional.
  • An optional parameter comes after every required parameter.
  • Inside the function, an omitted optional parameter holds the value undefined.
  • A default value is written with an equals sign after the parameter type.
  • A call that omits a default parameter uses the default value.
  • A call that passes a value for a default parameter uses that value instead.

In this example, quantity has a default value of 1 and note is optional. The first call passes only an item, so the quantity is 1 and no note is added. The second call passes its own quantity. The third call also passes a note, so the note joins the line in brackets.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What makes a parameter optional in TypeScript?