You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决TypeScript中动态访问类方法的TS7053类型错误?

修复TypeScript TS7053索引类型错误

针对你遇到的TS7053错误,有三种常见修复方案,具体如下:

方案一:用keyof约束数组元素类型

明确数组lista的元素类型为Bla类的键类型,让TypeScript能准确推导i的类型,从而识别this[i]是类的方法。

修改后的代码:

export class Bla {
  do1() {
    return 1;
  }

  do2() {
    // 用keyof Bla约束数组元素类型
    const lista: Array<keyof Bla> = ['do1'];
    lista.every((i) => {
      return this[i]();
    });
  }
}

注意:原代码中给箭头函数指定返回类型string会导致新的类型不匹配错误(do1返回number),需要一并移除,TypeScript会自动推导正确的返回类型。

方案二:给类添加索引签名

给Bla类添加字符串索引签名,允许用string类型的表达式索引类实例。根据类中方法的返回值,定义合适的索引签名:

export class Bla {
  // 添加索引签名,匹配类中方法的类型
  [key: string]: () => number;

  do1() {
    return 1;
  }

  do2() {
    const lista = ['do1'];
    lista.every((i) => {
      return this[i]();
    });
  }
}

如果类中有不同返回类型的方法,可以将索引签名的返回值改为unknown(不推荐用any,会丢失类型检查能力),比如[key: string]: () => unknown;。

方案三:类型断言(安全性低,不推荐)

手动将i断言为keyof Bla,强制TypeScript认可该索引的合法性,但这种方式不会校验数组中是否存在类中没有的键,存在类型安全隐患:

export class Bla {
  do1() {
    return 1;
  }

  do2() {
    const lista = ['do1'];
    lista.every((i) => {
      // 类型断言为keyof Bla
      return this[i as keyof Bla]();
    });
  }
}

内容的提问来源于stack exchange,提问作者Kaspacainoombro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:24:28