0
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.

【TypeScript】インデックスシグネチャのキーに変数を設定したい

Posted at

概要

インデックスシグネチャはインデックスシグネチャの記事にある通り、連想配列のような用途などでobject型を用いるものになります。
今回はこのインデックスシグネチャで、キーに変数を設定する場合に、どのように書けばよいかをメモ書きします。

実装例

以下のように、キー設定する変数を[]で囲みます。

const indexSignatureKeyType = () => {
  const key = { key1: "key1", key2: "key2", key3: "key3" };
  const sampleObj = {
    [key.key1]: 1,
    [key.key2]: 2,
    [key.key3]: 3,
  };
  // 1が取得できる
  const sample1 = sampleObj[key.key1];
  console.log(sample1);
}

その他参考

【TypeScript】インデックスシグネチャのオブジェクトで存在しないキーを指定した時の動作

0
0
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
0
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?