undefined
is a type that represents an uninitialized or missing value.null
is a type that represents an intentional absence of any object value.
Example 1: Assigning undefined
and null
let u: undefined = undefined; // OK, u is assigned undefined
let n: null = null; // OK, n is assigned null
Key Points:
- A variable of type
undefined
can only be assigned the valueundefined
. - A variable of type
null
can only be assigned the valuenull
.
Example 2: null
and undefined
with Strict Null Checks
If strictNullChecks
is enabled in TypeScript, null
and undefined
are not automatically assignable to other types like string
or number
.
let x: number = null; // Error if `strictNullChecks` is enabled
let y: string = undefined; // Error if `strictNullChecks` is enabled