Javascript感覚でTypescriptのコードを書いてたら???となったので覚書き
結論
Variable '****' implicitly has type 'any[]' in some locations where its type cannot be determined
と言われたら
ちゃんと型を指定しよう
- const array = [];
+ const array: number[] = [];
Typescriptの配列操作でエラーが出た
const array = [];
// Variable 'array' implicitly has type 'any[]' in some locations where its type cannot be determined. と怒られます
array.entries(); // メソッドは任意
Variable 'array' implicitly has type 'any[]' in some locations where its type cannot be determined
でググっても、コレというのものが引っかかりませんでした。(というより、エラーメッセージを真面目に読むべきでした)
同じことでハマる誰かのお役に立てば
対処法
配列の型を明記しましょう、というだけのお話でした
const array: number[] = [];
array.entries();
こんな感じで型を指定しないといけないですよということでした。
tsconfig.json の noImplicitAny
を有効化した場合はこの警告が出るようですね
{
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
}
もやもやしたが納得したところ
const array: any[] = [];
array.entries();
も
const array: any = [];
array.entries();
もエラーは出ない
any
は型の恩恵を放棄しているので、まあそうか
any[]
でもいいの?とは思いましたが、配列への暗黙的な決定がダメだっただけなので問題ないというわけですね
ちなみに
これはエラーでません。
const array = [];
array.push(0);
array.entries();
push
した変数の型で定義されるので、const array:number[] = []
と同じような扱いにしてくれます。これで逆に???になりましたが
(それならやっぱりany[]
もダメなんじゃないの?)
おわりに
const array = []
の時点で配列としてわかるし補完も効くから問題ないじゃん、と思ったのですが。
その思い込みのせいで少しハマりました。
横着せずに型は明記しましょう。