O'Reilly logo

TypeScript Blueprints by Ivo Gabe de Wolff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Checking null and undefined

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.

Guard against null and undefined

TypeScript has various ways to check whether a variable could be undefined or null. The next code block demonstrates them: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required