Undefined Versus Null
In this lesson, you will see the ubiquitous type undefined, which is used to define something that does not exist.
undefined
A variable declared but not initialized is undefined
. Undefined is not quite the same as the type null
. In both cases, an assignment can set undefined
or null
to a variable explicitly. The following code does not compile because the variable is consumed before initialization and TypeScript when configured to be strict, does not allow for interaction with an unassigned variable.
let variableNotInitialized:string;console.log(variableNotInitialized);
TypeScript must be made stricter in order to prevent it from assigning null or undefined to every type. You must set TypeScript’s strictNullChecks
option to true
to block the possibility implicitly assigning null and undefined to our variables (available since TypeScript 2.0).
// This code will work before TypeScript 2.0let numberOnlyNotNullOrUndefined: number = 123;numberOnlyNotNullOrUndefined = null;numberOnlyNotNullOrUndefined = undefined;console.log(numberOnlyNotNullOrUndefined)
Being forced to be explicit about all possible values forces developers to use union
or the question mark to optionally define the variable, which allows undefined. A nullable number is considered to be two types. Dual type (or more) is possible with a union. The union uses the pipe character between the main type (for example, a number) and null.
// This code would work before TypeScript 2.0let numberNullOrUndefined: number | null | undefined = 123;numberNullOrUndefined = null;numberNullOrUndefined = undefined;console.log(numberNullOrUndefined)
The union of any other type and undefined
makes the type optional. Using the ...