undefinedis a type that represents an uninitialized or missing value.nullis 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 nullKey Points:
- A variable of type
undefinedcan only be assigned the valueundefined. - A variable of type
nullcan 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