LoginSignup
19
11

More than 3 years have passed since last update.

keyof typeofの使い方 [TypeScript]

Last updated at Posted at 2020-09-08

やりたいこと

object等の呼び出しで Object[key] のようにするとき、key に動的な変数を入れたい。
上記をより美しく。

問題・エラー

今回の記事では、こちらのコードを修正します。
関数receivedStringValue()は、ランダムでStringの値を返す関数とします。


const object = {
    aaa: 'aaa',
    bbb: 'bbb',
    ccc: 'ccc',
};
// keyには動的に生成された値
const key: string = receivedStringValue();
const value = object[key];

こちらのコードでは、下記のエラーが出ます。

Element implicitly has an 'any' type because expression of type 'string' can't be used to

解決策

object に対して型を定義する

結論

key の型がわかるような object の型を定義する

interface StringKeyObject {
    // 今回はstring
    [key: string]: any;
}
const object: StringKeyObject = {
    aaa: 'aaa',
    bbb: 'bbb',
    ccc: 'ccc',
};

// keyには動的に生成された値
const key: keyof typeof object = receivedStringValue();
const value = object[key];

keyの型がstringだとあいまいなので、 keyof typeof object でしっかりと制限をかけることがポイントです。

最後まで読んでくださって、ありがとうございます。

参考記事

19
11
0

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
19
11