为什么 Javascript 绑定 returns 任何?
Why Javascript bind returns any?
在下面的代码中,调用了绑定方法,这样当从另一个 class 调用 bake
时 this.flavour
不会变成 undefined
。
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)
但是,一旦在函数 bake 上调用了 bind 方法,这种类型就变成了 any
。这意味着如果它的 属性 与接口定义 CakeEvent
不匹配,Typescript 将不会抛出编译错误。如果变成any
,界面CakeEvent
就是无用的浪费时间
returning any 背后的动机是什么?它不应该 return 相同类型的函数吗?
目前,防止这种情况发生的解决方法是什么?
来自 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;
我在 typescript 游乐场玩了一圈后发现的
只需在 TS 配置中将 strictBindCallApply
设置为 true。
引用如下:https://www.typescriptlang.org/docs/handbook/compiler-options.html
在下面的代码中,调用了绑定方法,这样当从另一个 class 调用 bake
时 this.flavour
不会变成 undefined
。
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)
但是,一旦在函数 bake 上调用了 bind 方法,这种类型就变成了 any
。这意味着如果它的 属性 与接口定义 CakeEvent
不匹配,Typescript 将不会抛出编译错误。如果变成any
,界面CakeEvent
就是无用的浪费时间
returning any 背后的动机是什么?它不应该 return 相同类型的函数吗?
目前,防止这种情况发生的解决方法是什么?
来自 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;
我在 typescript 游乐场玩了一圈后发现的
只需在 TS 配置中将 strictBindCallApply
设置为 true。
引用如下:https://www.typescriptlang.org/docs/handbook/compiler-options.html