In TypeScript, null
and undefined
are treated as distinct types. A variable of type null
means the absence of a value, while undefined
means a variable is declared but not yet assigned any value. In older versions of TypeScript, these types were treated as any
, which could lead to type safety issues.
Since TypeScript 2.0, null
and undefined
are strictly differentiated and treated as distinct types by default.
Example:
let x: string | null = null; let y: string | undefined = undefined; x = 'Hello'; // OK y = 'World'; // OK x = undefined; // Error, 'undefined' is not of type 'string | null'
You can also change the behavior by enabling the strictNullChecks
option in the tsconfig.json
, which enforces stricter handling of null
and undefined
in other types. With strictNullChecks
, null
and undefined
must be explicitly assigned to appropriate types to avoid errors.