在对象字面量中使用自引用
ThisType
按预期工作。打字稿编译器可以访问对象中定义的属性,并在尝试访问未定义的属性时发出错误消息。
function define<A>(options: A & ThisType<A>) {}
define({
a() {},
w1: function () {
this.a(); // ok
this.b(); // error
return () => {
this.a(); // ok
this.b(); // error
};
}
});
有没有办法让打字的工作方式与包装函数相同?
function wrapper(fn: () => any) { return fn; }
define({
a() {},
w2: wrapper(function () {
this.a(); // should be ok
this.b(); // should be error
}),
});
这只是一个关于键入的问题,在运行时
this
具有正确的值并且按预期工作。
我尝试使用
function
和箭头函数的组合以及像 function wrapper<T>(fn: (this: T) => any) { return fn; }
这样的泛型类型,但是 T
应该是什么?