In the following code, the bind method has been called so that this.flavour does not become undefined when bake is called from another class.
interface CakeEvent{
onBake(flour:number):void
}
class Cake {
private listener: CakeEvent
addChocolate(listener: CakeEvent) {
this.listener = listener
}
onBake(flour: number) {
this.listener.onBake(flour)
}
}
class Chocolate {
private flavour = 'vanilla'
private bake(flour:number) {
console.log(this.flavour, flour)
}
constructor(private cake: Cake) {
const listener: CakeEvent = {
onBake: this.bake.bind(this) // <- Here
}
this.cake.addChocolate(listener)
}
}
const cake = new Cake()
const choco = new Chocolate(cake)
cake.onBake(4564)
However, as soon as the method bind is called on the function bake, this type becomes any. This means that Typescript will not throw a compilation error if its property does not match the interface definition CakeEvent. If it becomes any, the interface CakeEvent is a useless waste of time.
What is the motivation behind returning any? shouldn't it return the same type of function?
Currently, what is the workaround to prevent this to become any?
from node_modules/typescript/lib.es5.d.ts
/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
I found it after playing around in the typescript playground
Simply set strictBindCallApply to true in TS config.
Here is the reference: https://www.typescriptlang.org/docs/handbook/compiler-options.html
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