Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 为什么映射类型在类内调用时会触发编译错误_Typescript_Mapped Types - Fatal编程技术网

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 
  }
  
}