【问题标题】:Compiler Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Igame'编译器错误 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“Igame”
【发布时间】:2021-12-19 13:54:51
【问题描述】:

完整的错误信息:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Igame”类型。 在“Igame”类型上找不到带有“字符串”类型参数的索引签名。 ts(7053)

界面:

export interface Igame {
  id: number;
  isStart: boolean;
  isFinish: boolean;
}

在类组件中

public games: Igame[] = [];

public gameAction(id: number, action: string): void {
    const index = this.games.findIndex((game) => game.id === id);
    this.games[index][action] = true;
}

错误在这段代码下划线:

this.games[index][action]

函数gameAction用于改变游戏状态。 例如

gameAction(1, 'isStart')

(游戏 #1 开始)

【问题讨论】:

  • 你到底想用 this.games[index][action] 这一行做什么?
  • 函数gameAction用于改变游戏状态。例如 gameAction(1, 'isStart') (游戏 #1 开始)

标签: angular typescript


【解决方案1】:

我通过向接口添加索引签名解决了编译错误,如下代码:

export interface Igame {
   [key: string]: any;
   id: number;
   isStart: boolean;
   isFinish: boolean;
}

【讨论】:

    【解决方案2】:

    this.games[index] 将为您提供您在上一行中找到索引的 Igame。

    所以,你正在做相当于

    const index = this.games.findIndex((game) => game.id === id);
    const Igame game = this.games[index];
    const game[action] = true;
    

    这将在第三行失败,因为 Igame 不是数组, 或者类似数组的对象,接口上没有这样的签名。

    【讨论】:

    • 感谢您的回答。当用字符串替换'action'参数时,编译OK。像这样:this.games[index]['isStart'] = true;
    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2021-08-28
    • 2021-03-17
    • 2021-04-20
    • 1970-01-01
    • 2021-10-19
    • 2020-11-13
    • 2019-12-17
    相关资源
    最近更新 更多