1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TSエラー】型 'string' の式を使用して型にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。 型 'string' のパラメーターを持つインデックス シグネチャが型 ' に見つかりませんでした。

1
Posted at

はじめに

ReactでTypeScriptを書いていたとき、タイトルのエラーに遭遇したので備忘録として残します。

発生した問題

オブジェクトから、メソッドの引数に対応したkeyのvalueを取得するとき、エラーが発生しました。
以下再現コードです。

// 飼っている猫のname(key)に対応するageを取得したい

const catAge = (name: string) => {
    const { age } = catObject[name];
    return age;
};

const catObject = {
    虎丸: {
        age: 3,
        breed: "キジトラ",
    },
    ミケ: {
        age: 7,
        breed: "三毛猫",
    },
};

エラー

型 'string' の式を使用して型 '{ 虎丸: { age: number; breed: string; }; ミケ: { age: number; breed: string; }; }' にインデックスを付けることはできないため、要素は暗黙的に 'any' 型になります。
  型 'string' のパラメーターを持つインデックス シグネチャが型 '{ 虎丸: { age: number; breed: string; }; ミケ: { age: number; breed: string; }; }' に見つかりませんでした。

解決方法

結論から言うと、今回はindex signatureを使用して解決しました。
Recoedを使用する解決策もありましたが、今回はRecoedを使うメリット(key をユニオン型で指定することが可能)があまり活かせないと判断しました。

以下、解決したコードです。

interface Cat {
    [name: string]: { age: number; breed: string };
}

const catObject: Cat = {
    虎丸: {
        age: 3,
        breed: "キジトラ",
    },
    ミケ: {
        age: 7,
        breed: "三毛猫",
    },
};

const catAge = (name: string) => {
    const { age } = catObject[name];
    return age;
};

interfaceを使用して、オブジェクトの取り得る値を記述しておくことでエラーを回避できます。

参考サイト

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?