typescript 如何在class中 返回this[key]?

class Obj {
  constructor() {}
  a() {}
  b() {}
  c() {}
  plugins: Record<string, Function> = {
    d() {},
    e() {},
  };
  useFunc(name: string) {
    return this[name] || this.plugins[name];
  }
}
const theObj = new Obj();

结果报错:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Obj'.
  No index signature with a parameter of type 'string' was found on type 'Obj'.
阅读 2k
5 个回答

试试

useFunc(name: string) {
  return (this as any)[name] || this.plugins[name];
}

原因是 mediaType 的类型未知,ts 在类型检测的时候发现不了需要确保name是Obj的key
添加这个name as keyof Obj, 将其设置一下

class Obj {
  constructor() {}
  a() {}
  b() {}
  c() {}
  plugins: Record<string, Function> = {
    d() {},
    e() {},
  };
  useFunc(name: string) {
    return this[name as keyof Obj] || this.plugins[name];
  }
}




const theObj = new Obj();
console.log(theObj.useFunc('a'))

useFunc 参数类型应为 (keyof typeof this) | (keyof typeof this.plugins) ,或者也可以在取值的时候用 as 断言键的类型。

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏