本文へスキップ
BecomeCoder

TypeScriptのエラー · エラー11

TS7053: implicit 'any' type ― 添字アクセスの型が定まらない

インデックス型({ [key: string]: T })を定義していないオブジェクトに、string 型の変数で添字アクセスすると出ます(noImplicitAny 有効時)。

出るコード

const scores = { a: 1, b: 2 };
const key = "c";
console.log(scores[key]);   // key は string 型

エラーメッセージ

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; b: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ a: number; b: number; }'.

直し方

キーをリテラル型で絞る(keyof typeof scores)か、scores as Record<string, number> のように明示します。