optional function parameter typescript code example
Example 1: typescript optional parameters
sayHello(hello?: string) {
console.log(hello);
}
sayHello();
sayHello('world');
Example 2: typescript default parameter
sayHello(hello: string = 'hello') {
console.log(hello);
}
sayHello();
sayHello('world');
Example 3: typescript optional parameters
sayHello(hello: string = 'hello') {
console.log(hello);
}
sayHello();
sayHello('world');
Example 4: how to make a parameter optional in typescript
function foo(x?: number) {
console.log("x : "+ x);
}
foo();
foo(6);
Example 5: typescript default parameter
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
Example 6: typescript make function argument optional
function multiply(a: number, b: number, c?: number): number {
if (typeof c !== 'undefined') {
return a * b * c;
}
return a * b;
}