LoginSignup
18
15

More than 3 years have passed since last update.

Object[key] を使うと発生する、Element implicitly has an 'any' type because type 'typeof *****' has no index signature. を回避する方法

Last updated at Posted at 2020-01-23

はじめに

TypeScript使ってて、任意のオブジェクトが持つ、キーでループさせたいときがあります。
すると、どうしてもブラケット使わなくちゃならない。Object[key]みたいな。
そういうことするとTypeScriptはえらいから、

Element implicitly has an 'any' type because type 'typeof *****' has no index signature.

なんて言って、注意してくれるわけですよ、これを回避したい。

サンプルコード

  const Foo = {
    one: 1,
    two: 2,
    three: 3,
    four: 4,
    five: 5,
  };

  const bar: object = Object.keys(Foo).reduce((acc: any, key: any) => {
    acc[key] = Foo[key];
    return acc;
  }, {});

コンパイルすると、

Element implicitly has an 'any' type because type 'typeof Foo' has no index signature.

って言う。あーうぜえ。

回避する方法

  const Foo = {
    one: 1,
    two: 2,
    three: 3,
    four: 4,
    five: 5,
  };

  const bar: object = Object.keys(Foo).reduce((acc: any, key: any) => {
    acc[key] = Foo[key as keyof typeof Foo];
    return acc;
  }, {});

keyを"keyof typeof Foo"でasしてやる。
ここでのkeyはFooの要素だよってコンパイラに教えてやるってことらしい。
なんかキモイけどしょうがない。

参考

https://github.com/microsoft/TypeScript/issues/19137
https://typescript-jp.gitbook.io/deep-dive/type-system/moving-types#knokyapucha
https://qiita.com/gonta/items/fb7b9e6d0f12060c27d6
https://qiita.com/Nossa/items/e01d0bce67b760c0bcb9

↓ここにもあった
https://qiita.com/SoraKumo/items/67a967bff996c3efb091#3-%E3%82%A4%E3%82%AD%E3%81%A3%E3%81%A6strict%E3%82%92true%E3%81%AB%E3%81%97%E3%81%9F%E3%81%A8%E3%81%8D%E3%81%AB%E8%A8%AA%E3%82%8C%E3%82%8B%E8%A9%A6%E7%B7%B4%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%AE%E3%82%AD%E3%83%BC

18
15
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
18
15