[TypeScript]エラー「Variable ‘xxx’ implicitly has type ‘any[]’ in some locations where its type cannot be determined.」の解決方法

TypeScript

どうも、ちょげ(@chogetarou)です。

TypeScriptでコードを実行したら、「Variable ‘xxx’ implicitly has type ‘any[]’ in some locations where its type cannot be determined.」というエラーが出ました。

色々と試してみた結果、なんとか解決できたので、この記事では私が解決できた方法を紹介します。

スポンサーリンク

解決方法

エラー「Variable ‘xxx’ implicitly has type ‘any[]’ in some locations where its type cannot be determined.」は、配列の型を明記することで解決できました。

以下は、エラーが発生したコードです。

function isEmpty(arr: any[]) {
    return arr.length === 0;
}

let array = []; //エラー発生

console.log(isEmpty(array));

上記のエラーが発生している部分の配列の型を明記することで、エラーが解消されました。

function isEmpty(arr: any[]) {
    return arr.length === 0;
}

let array: number[] = []; //エラーなし

console.log(isEmpty(array));

空の配列の状態では、型が分からずエラーが発生してしまいます。

なので、空の配列を宣言する際は、型を明記する必要があります。

スポンサーリンク

まとめ

「Variable ‘xxx’ implicitly has type ‘any[]’ in some locations where its type cannot be determined.」は、空の配列の宣言時に、配列の型を定義することで解決できます。

コメント

タイトルとURLをコピーしました