Undefined Versus Null
Explore the distinctions between undefined and null in TypeScript, understand strictNullChecks, and learn how to use union types and optional parameters to write clearer, safer code.
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.
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).
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.
The union of any other type and undefined makes the type optional. Using the question mark ...