24. How does TypeScript handle null and undefined? Explain with examples.

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.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.