function as parameter typescript code example
Example 1: typescript parameter function type
class Foo {
save(callback: (n: number) => any) : void {
callback(42);
}
}
var foo = new Foo();
var strCallback = (result: string) : void => {
alert(result);
}
var numCallback = (result: number) : void => {
alert(result.toString());
}
foo.save(strCallback);
foo.save(numCallback);
Example 2: typescript function as parameter
function createPerson(name: string, doAction: () => void): void {
console.log(`Hi, my name is ${name}.`);
doAction();
}
createPerson('Bob', waveHands());
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' });
Example 4: typescript annotate return type
function add(x: number, y: number): number {
return x + y;
}