1// Default Parameters
2sayHello(hello: string = 'hello') {
3 console.log(hello);
4}
5
6sayHello(); // Prints 'hello'
7
8sayHello('world'); // Prints 'world'
1function createPerson(name: string, doAction: () => void): void {
2 console.log(`Hi, my name is ${name}.`);
3 doAction(); // doAction as a function parameter.
4}
5
6// Hi, my name is Bob.
7// performs doAction which is waveHands function.
8createPerson('Bob', waveHands());
1function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
2 const name = first + ' ' + last;
3 console.log(name);
4}
5
6sayName({ first: 'Bob' });
1class Foo {
2 save(callback: (n: number) => any) : void {
3 callback(42);
4 }
5}
6var foo = new Foo();
7
8var strCallback = (result: string) : void => {
9 alert(result);
10}
11var numCallback = (result: number) : void => {
12 alert(result.toString());
13}
14
15foo.save(strCallback); // not OK
16foo.save(numCallback); // OK
1// define your parameter's type inside the parenthesis
2// define your return type after the parenthesis
3
4function sayHello(name: string): string {
5 console.log(`Hello, ${name}`!);
6}
7
8sayHello('Bob'); // Hello, Bob!