I've got the following code:
class A {
constructor(public n: number) {}
defaultFn(a: number): number {
return a + 1;
}
doStuff(callback?): number {
return callback ? callback(this.n) : this.defaultFn(this.n);
}
}
How can I tell TypeScript that the optional callback
function passed to doStuff
method should have the same signature as defaultFn
method?
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
One more option is to "query" type of defaultFn
. In this case you won't need to maintain the type of callback manually:
class A {
constructor(public n: number) {}
defaultFn(a: number): number {
return a + 1;
}
doStuff(callback?: A['defaultFn']): number {
return callback ? callback(this.n) : this.defaultFn(this.n);
}
}
The result of A['deafultFn']
is (a: number) => number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With