51
33

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で、Object[key]とすると出るIndex signature of object type implicitly has an 'any' type.を正しく回避する

Last updated at Posted at 2016-10-27

#はじめに
Typescriptで、 Object[key] と書くと出る
Index signature of object type implicitly has an 'any' type. を正しく回避したい時の一つの方法
参考urlを読めば分かるのだが、検索してもなかなか見つけられなかったのでここに記す

筆者は、redux-formでチェックボックスを作る際にハマった

Compilerに型を教えてやる

interface pokemon {
  PIKACHU: boolean,
  RAICHU: boolean,
  YADORAN: boolean
  \[key: string]: boolean
}

let key: string = 'PIKACHU';
let pikachu: string = pokemon[key];

さらに、booleanではないvalueを定義すると、Compilerが怒ってくれる

Property 'PIDHION' of type 'number' is not assignable to string index type 'boolean'.

補足: \[key: string]: boolean <= 先頭の""は、不要なのだが、code-block内ではこうするしかなかった

おまけ: よく見つかる解法

コンパイラのオプションに以下を渡す

--suppressImplicitAnyIndexErrors

....だが、これは使いたくない

###参考
http://stackoverflow.com/questions/32968332/how-do-i-prevent-the-error-index-signature-of-object-type-implicitly-has-an-an

51
33
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
51
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?