0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

noUncheckedIndexedAccess を有効にする際は "strict": true も指定する

Posted at

noUncheckedIndexedAccess を有効にしても配列アクセスでエラーにならなかったので、その現象が起きた際のメモです。

"strict": true を指定する

たとえば、以下のコードでは長さが 2 しかない配列の添字に 5 を指定しているため undefined となり、その次の行で実行時エラーになってしまいますが、これを TypeScript のエラーとして検知したいわけです。

Hello.tsx
const arr: string[] = ["foo", "bar"];
const item = arr[5];
console.log(item.toUpperCase());

このようなコードを書いた場合、 "strict": true が指定されていない場合、エラーが発生しません。

以下のように "strict": true を指定すると、'xxxx' is possibly 'undefined'. というエラーが発生するようになります。

tsconfig.json
 {
   "compilerOptions": {
     "noUncheckedIndexedAccess": true,
+    "strict": true,
     (中略)
   },
   "include": ["src/**/*"]
 }
src/Hello.tsx:31:15 - error TS18048: 'item' is possibly 'undefined'.

31   console.log(item.toUpperCase());
                 ~~~~

これは、"strict": true を指定すると strictNullChecks が ON になることによる効果かと思われます。

皆さんも noUncheckedIndexedAccess を有効にする際は "strict": true が指定されているかどうかチェックするようにしてみてください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?