Typescript 为什么映射类型在类内调用时会触发编译错误
这是我的示例代码 在类内调用Typescript 为什么映射类型在类内调用时会触发编译错误,typescript,mapped-types,Typescript,Mapped Types,这是我的示例代码 在类内调用get,在类外调用方法时会触发错误 知道为什么吗 type DefinedKeys<T> = keyof { [K in keyof T as undefined extends T[K] ? never : K]: K } class MyAbstractClass { get<K extends keyof this & DefinedKeys<this>>(key: K): this[K] { ret
get
,在类外调用方法时会触发错误
知道为什么吗
type DefinedKeys<T> = keyof {
[K in keyof T as undefined extends T[K] ? never : K]: K
}
class MyAbstractClass {
get<K extends keyof this & DefinedKeys<this>>(key: K): this[K] {
return this[key];
}
}
class MyClass extends MyAbstractClass {
foo: string = "ok";
optional?: string;
test() {
this.get('foo'); // Doesn't work
}
}
const instance = new MyClass();
const yepItsWorks: string = instance.get("foo"); // Ok
type DefinedKeys=keyof{
[K在T的键中作为未定义的扩展T[K]?从不:K]:K
}
类MyAbstractClass{
get(key:K):这个[K]{
返回此[键];
}
}
类MyClass扩展了MyAbstractClass{
foo:string=“确定”;
可选?:字符串;
测试(){
这个.get('foo');//不起作用
}
}
const instance=new MyClass();
const-yepItsWorks:string=instance.get(“foo”);//好啊
我的猜测是,使用
test
执行上下文是未知的
TypeScript正确地假设您可以使用instance.test.call(otherThis)
或类似工具使用不同的this
调用该方法。如果您显式地键入此,它会工作
class MyClass extends MyAbstractClass {
foo: string = "ok";
optional?: string;
test(this: MyClass) {
this.get('foo'); // Works now
}
}
但这并不十分一致-以下内容也应该绑定此,但它并没有按预期工作
class MyClass extends MyAbstractClass {
foo: string = "ok";
optional?: string;
test = () => {
this.get('foo'); // Doesn't work
}
}