TypeScript 2.0 introduces two new types: null
and undefined
. You have to set the compiler option strictNullChecks
to true
to use these types. In this mode, all other types cannot contain undefined
or null
anymore. If you want to declare a variable that can be undefined
or null
, you have to annotate it with a union type. For instance, if you want a variable that should contain a string
or undefined
, you can declare it as let x: string | undefined;
.
Before assignments, the type of the variable will be undefined
. Assignments and type guards will modify the type locally.
TypeScript has various ways to check whether a variable could be undefined
or null
. The next code block demonstrates them:
let x: string | null | undefined = ...; if (x !== null) { // x: string | undefined } if (x !== undefined) { // x: string | null } if (x != null) { // x: string } if (x) { //...