In this article we will learn about some of the frequently asked TypeScript programming questions in technical like “typescript function as parameter” Code Answer’s. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error or stack handling on typescript was simple and easy. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in Typescript. Below are some solution about “typescript function as parameter” Code Answer’s.
typescript default parameter
xxxxxxxxxx
1
// Default Parameters
2
sayHello(hello: string = 'hello') {
3
console.log(hello);
4
}
5
6
sayHello(); // Prints 'hello'
7
8
sayHello('world'); // Prints 'world'
typescript default parameter
xxxxxxxxxx
1
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
2
const name = first + ' ' + last;
3
console.log(name);
4
}
5
6
sayName({ first: 'Bob' });
typescript function as parameter
xxxxxxxxxx
1
function 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.
8
createPerson('Bob', waveHands());
typescript pass a function as an argunetn
xxxxxxxxxx
1
class Foo {
2
save(callback: (n: number) => any) : void {
3
callback(42);
4
}
5
}
6
var foo = new Foo();
7
8
var strCallback = (result: string) : void => {
9
alert(result);
10
}
11
var numCallback = (result: number) : void => {
12
alert(result.toString());
13
}
14
15
foo.save(strCallback); // not OK
16
foo.save(numCallback); // OK
typescript function type
xxxxxxxxxx
1
// define your parameter's type inside the parenthesis
2
// define your return type after the parenthesis
3
4
function sayHello(name: string): string {
5
console.log(`Hello, ${name}`!);
6
}
7
8
sayHello('Bob'); // Hello, Bob!
typescript annotate return type
xxxxxxxxxx
1
function add(x: number, y: number): number {
2
return x + y;
3
}