default value function typescript code example

Example 1: typescript optional parameters

// Optional Parameters
sayHello(hello?: string) {
	console.log(hello);
}

sayHello(); // Prints 'undefined'

sayHello('world'); // Prints 'world'

Example 2: typescript default parameter

// Default Parameters
sayHello(hello: string = 'hello') { 
    console.log(hello); 
}

sayHello(); // Prints 'hello'

sayHello('world'); // Prints 'world'

Example 3: typescript default parameter

function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
  const name = first + ' ' + last;
  console.log(name);
}

sayName({ first: 'Bob' });