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

TypeScriptの配列のKeyを変数で指定したい時

Last updated at Posted at 2020-01-31

typescriptの配列をkey指定したい時

test.ts

let example = 'like';
let exampleArray = { like: 'apple'}

console.log(exampleArray[example]);

上記コードだと

Element implicitly has an 'any' type because type '{ like: string; }' has no index signature.

indexのsignatureは勝手にanyになるため型指定してあげないとだめ。
参考

要するにkeyにどの型が入って、要素になんの型が入っているかを指定してあげる。

test.ts

let example = 'like';
let exampleArray: { [keys: string]: string; } = { like: 'apple' }

console.log(exampleArray[example]); // 'apple'

Keyはnumberとstringしか指定出来ない。keyはanyとして指定は出来ないので

test.ts

let exampleArray = { 1: 'apple', '2': 'orange' };

当たり前だが上記のような場合は変数が使えなくなる。

要素にはなんの値でも代入出来る。なので数値も文字列も入れるのであれば要素側はany型の指定も可能。

なので先程も記述したが
Keyはnumberとstringしか指定出来ない。keyはanyとして指定は出来ないので

test.ts

let exampleArray {[keys: string | number ]: string;} = { 1: 'apple', '2': 'orange' };
// ↑のようにorも使えない。

//逆に要素側は
let exampleArray {[keys: string]: string | number;} = { '1': 'apple', '2': 130 };
//のように指定出来る。

※ただ要素側の返り値がstringを要求している場合or記述は当たり前のようにエラー吐くので注意

おまけ:色んな所で使用するのであればinterfaceとして作って置くことも出来る

test.ts
interface ArrayType {
  [index: string]: string;
}

let example = 'like';
let exampleArray: ArrayType = { like: 'apple' }

console.log(exampleArray[example]); // 'apple'


最後に

ソース自体を調べたわけではなく自分の知りたい範囲で実際のコードでテストしたのみです。
間違い、ご指摘内容があれば気軽にお願いいたします

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