让打字稿知道对象是什么类型
我在写一个允许用户指定回调的库。像这样:让打字稿知道对象是什么类型
interface IParams {
context: any;
okCallback: (value: string) => void
... etc ...
}
class MsgBox {
static getInput(params: IParams) {
....
okCallback.call(params.context, value);
}
}
上下文的目的是将回调放在上下文中。因此,例如我可以这样做:
MsgBox.getInput({
context: this,
okCallback(value) {
this.accessToEnclosingClass
}
}
由于回调需要访问调用类的属性。这使得它比在所有地方使用$ .proxy()更方便。
这工作正常,但是,问题与打印机编译器。在回调打字稿中不知道this
的类型,所以对待它就像任何类型,并且不会为我进行任何类型检查,这会导致很多挫折。
有没有办法让Typescript编译器知道在这种情况下this
的类型是什么?我可以这样做:
okCallback(value) {
const self = this as EnclosingClassType;
self.accessToEnclosingClass
}
哪些工作,但我宁愿使用this
(因为否则是不小心使用this
,从而可能导致非编译型类型错误的机会
当然这一点。一个简单的例子,当this
环境未定义okCallback挑战发生,但作为一个单独的函数。
在这个任何建议或想法?
你可以只用一个arrow function节省的this
背景:
MsgBox.getInput({
context: this,
okCallback: (value) => {
this.accessToEnclosingClass
}
}
编译器(和IDE)会明白,也因此不会把this
为已任。
箭头函数不仅仅是类型检查:你不能再使用'okCallback.call(aDifferentThis)'在'okCallback'内改变'this'上下文。这意味着'getInput'可以做'okCallback(value)',并且你可以用'(value:string)=> void'代替'IParams',因为'context'字段是不需要的。 –
在TS 2.0中可以输入'this'。请参阅https://github.com/Microsoft/TypeScript/pull/6739。 – 2016-08-13 06:56:07