typescript overloading code example
Example 1: typescript default parameter
// Default Parameters
sayHello(hello: string = 'hello') {
console.log(hello);
}
sayHello(); // Prints 'hello'
sayHello('world'); // Prints 'world'
Example 2: how to make a parameter optional in typescript
// Optional parameter
function foo(x?: number) {
console.log("x : "+ x);
}
foo();
foo(6);
Example 3: function overload in ts
Overloaded Funcitons:
Set of different functions which have same name.
type Both = string | number;
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: Both, b: Both) {
if (typeof a === 'string' || typeof b === 'string') {
return a.toString() + b.toString();
}
return a + b;
}
const res = add('Joyous ', '21');
console.log(res);