Angular 15中嵌套对象索引的TypeScript TS7053错误解决
解决TypeScript索引类型不匹配错误(TS7053)
这个错误的核心原因是:gameName 是通用的 string 类型,但 GAMES_INFO 的键是特定的字面量类型('skyroads' 或 'prehistorik2'),TypeScript不允许用宽泛的string去索引具体的键类型,避免潜在的错误。以下是几种可行的解决方法:
方法1:约束gameName的类型为GAMES_INFO的键类型
先提取GAMES_INFO的键类型,再将gameName限定为该类型,或者在使用时做类型断言:
// 提取GAMES_INFO的键类型 type GameKey = keyof typeof GAMES_INFO; // 情况1:如果gameName是可控变量,直接声明为GameKey类型 const gameName: GameKey = 'skyroads'; this.gameInfo = dic.GAMES_INFO[gameName]; // 情况2:如果gameName来自用户输入(原始类型为string),先做有效性检查再断言 const userInput: string = 'skyroads'; if (userInput in dic.GAMES_INFO) { this.gameInfo = dic.GAMES_INFO[userInput as GameKey]; } else { // 处理无效游戏名称的逻辑,比如提示用户输入错误 }
这种方法最严谨,能保证类型安全,同时保留IDE的类型提示。
方法2:为GAMES_INFO添加索引签名
调整GAMES_INFO的类型定义,既保留具体键的类型提示,又允许用string作为索引:
// 先定义单个游戏信息的类型 type GameDetail = { name: string; genre: typeof GAMES_GENRES[keyof typeof GAMES_GENRES]; year: number; wiki: string; }; // 定义GAMES_INFO的类型:同时包含索引签名和具体键的类型 const GAMES_INFO: { [key: string]: GameDetail } & { skyroads: GameDetail; prehistorik2: GameDetail; } = { skyroads: { name: 'Sky Roads', genre: GAMES_GENRES.action, year: 1993, wiki: 'https://en.wikipedia.org/wiki/SkyRoads_(video_game)', }, prehistorik2: { name: 'Prehistorik 2', genre: GAMES_GENRES.arcade, year: 1993, wiki: 'https://en.wikipedia.org/wiki/Prehistorik_2', }, };
这样修改后,直接用string类型的gameName索引GAMES_INFO就不会报错,同时依然能获得具体键的类型提示。
方法3:直接使用类型断言(快速但需注意风险)
如果能确保gameName一定是GAMES_INFO的有效键,可以直接做类型断言跳过检查:
this.gameInfo = dic.GAMES_INFO[gameName as keyof typeof GAMES_INFO];
注意:如果gameName是无效值,这种方法会返回undefined,需要自己处理后续逻辑,避免出现空值错误。
内容的提问来源于stack exchange,提问作者Yoni Mayer
相关产品推荐
相关产品推荐

