104
55

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 3 years have passed since last update.

Object等の呼び出しでkeyに動的な変数を使う [TypeScript]

Last updated at Posted at 2019-08-30

やりたいこと

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

問題・エラー

何も考えずに下記のように書くと、

const object = {
    aaa: 'aaaa',
    bbb: 'bbb',
};
// 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 index type '{ aaa: string; bbb: string; }'.

解決策

object に対して型を定義する

よくない例

このエラーは、key に規則性がない(any型)、であるためにでているエラーなので、下記のような型定義ではエラーは治らない。

interface AB {
    aaa: string;
    bbb: string;
}
const data: AB = {
    aaa: 'aaaa',
    bbb: 'bbb',
};
const key: string = receivedStringValue;
const value = data[key];

結論

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


interface StringKeyObject {
    // key に string、value も string が返る
    [key: string]: string;

    // value には string 以外も渡せる
    // ex) number, unknown, any, ...
    // [key: string]: unknown;
}
const object: StringKeyObject = {
    aaa: 'aaaa',
    bbb: 'bbb',
};
// keyには動的に生成された値
const key: string = receivedStringValue;
const value = object[key];

(StringKeyObject ... もっと良い命名とかあれば教えてください…)

参考

Typescriptで、Object[key]とすると出るIndex signature of object type implicitly has an 'any' type.を正しく回避する

104
55
2

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
104
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?