LoginSignup
4
2

More than 3 years have passed since last update.

TypeScript:"strictNullChecks"について

Last updated at Posted at 2021-02-04

概要

TypeScript を勉強するにあたり、プログラミング初心者の私が詰まった点をメモに残す。
間違いがあれば教えていただけると幸いです。

環境

typescript: 4.1.2

考察

JavaScript はプログラムの変数が意図的に undefinednull を保持する柔軟な言語である。これらの型を保証し、より安全に開発を進める助けとなるのが TypeScript である。

const myExample = document.getElementById("example");
myExample.innerHTML = "Hello World!";

TypeScript を介してこれを実行してもエラーは起きない。
ID "example"を検索しようとしたときに存在しない場合は、myExample は nullとなり、null.innerHTML は読み取れない。

Uncaught TypeError: Cannot read property ‘innerHTML’ of null

VSCode などの TypeScript をサポートする IDE でメソッドにカーソルを合わせると、次のように表示される。

(method) Document.getElementById(elementId: string): HTMLElement

実行時には二つの可能な値(null or HTMLElement オブジェクト)があるが、コンパイル時に TypeScript は、戻り値が常に単一な型になる。これは「null 許容値」の概念があるからである。
この動作を有効にするために必要なのは、tsconfig.json"strictNullChecks”: true(または“strict”: true)を設定する。これにより、エラーが生じる。

[ts] Object is possibly ‘null’

先程と同じようにメソッドにカーソルを合わせると、下記のようになる。

(method) Document.getElementById(elementId: string): HTMLElement | null

HTMLElement と null の共用型となっていることが分かる。
if などを用いて、真である事を確認することで、エラーがなくなる。

const myExample = document.getElementById("example");
if (myExample) {
  myExample.innerHTML = "Hello World!";
}

MicroSoft の TypeScript チームは、"strictNullChecks”を有効にする事を勧めている。
より高品質なコードを書くことができるので、私も使っていきたい。

参考

書籍「実戦 TypeScript-BFF と Next.js&Nuxt.js の型定義- 著者 吉井健文」
https://jameshenry.blog/typescript-null-and-undefined-types/

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