概要
https://www.typescriptlang.org/tsconfig#noImplicitAny
{
"noImplicitAny": true
}
暗黙的にany
になる値をエラーにします。
any
は型の機能が一切効かなくなる型な上にany
はどんどん他のオブジェクトの型に侵食して増殖するので、基本的に使わないに越したことはありません。
詳細
const obj = {};
const hoge = obj["hoge"];
const arr = [];
const item = arr[0];
このコードの定数hoge
は型がany
になります。
また、arr
はany[]
になります。
これらはこのオプションをtrue
にすると以下のようなエラーでコンパイルが失敗します。
index.ts:14:14 - error TS7053: Element implicitly has an 'any' type because expression of type '"hoge"' can't be used to index type '{}'.
Property 'hoge' does not exist on type '{}'.
14 const hoge = obj["hoge"];
~~~~~~~~~~~
index.ts:16:7 - error TS7034: Variable 'arr1' implicitly has type 'any[]' in some locations where its type cannot be determined.
16 const arr1 = [];
~~~~
index.ts:17:14 - error TS7005: Variable 'arr1' implicitly has an 'any[]' type.
17 const item = arr1[0];
エラー回避するために
回避するためには、以下のように明示的に型を書くようにします。
const obj: Record<string, number> = {};
const hoge = obj["hoge"];
const arr1: string[] = [];
const item = arr1[0];
あとは、下記のように関数の引数なども同様です。
noImplicitAny - TypeScript Deep Dive 日本語版
逆に明示的に指定すれば OK
const obj: any = {};
const hoge = obj["hoge"];
const arr: any = [];
const item = arr[0];
逆に、上記のように明示的に指定する場合もコンパイルが通ります。
つまり、「あんまり何も考えてないけど気づかないうちにany
になっちゃった」みたいな状態を避けることができます。