LoginSignup
3
4

More than 3 years have passed since last update.

Typescriptの配列は横着せずに型を明記しよう

Last updated at Posted at 2019-08-05

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 を有効化した場合はこの警告が出るようですね

tsconfig.json
{
    "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 = [] の時点で配列としてわかるし補完も効くから問題ないじゃん、と思ったのですが。
その思い込みのせいで少しハマりました。
横着せずに型は明記しましょう。

3
4
0

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
3
4