TypeScript Reference ยท Primitive and Special Types
The TypeScript null type
Reference for null in TypeScript: the null type, strictNullChecks, narrowing with === null, ?? and ?., null versus undefined and common API patterns.
null is a value that means "deliberately no value", and null is also the name of its type. With strictNullChecks on (part of strict, and the default in modern projects) null is not assignable to other types, so a variable that may hold it has to say so with a union such as string | null.
The compiler then forces you to handle the empty case before using the value. This removes the classic "cannot read properties of null" crash from the type checker's point of view.
let name: string | null = null; name = "Ada";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
let a: null = null; let b: string | null = null; function f(x: number | null): void { /* ... */ }
| Form | Description |
|---|---|
null (type) |
Contains only the value null. |
T | null |
A value that may be missing. |
x === null |
Precise check that narrows T | null to T. |
x == null |
Matches both null and undefined. |
x! |
Non-null assertion; removes null and undefined without a runtime check. |
Usage notes
typeof nullis"object". This is an old JavaScript quirk. Compare with=== nullinstead of usingtypeof.- Without
strictNullChecks,nullis assignable to everything and the type is effectively invisible. Always enable it. - Prefer one empty value. Many codebases use
undefinedfor "not provided" and reservenullfor "explicitly empty" (databases, JSON, DOM APIs). Mixing both in one type (T | null | undefined) invites bugs. - Operators.
??replacesnullandundefinedonly, unlike||which also replaces0and"".?.stops at either. - JSON round trips.
nullsurvivesJSON.stringify;undefinedproperties are dropped. - Filtering.
.filter(Boolean)does not change the array type; use a type predicate as above. - DOM.
document.querySelectorreturnsElement | null; check or assert before use. - Error messages. Possible null reads report TS18047 ("'x' is possibly 'null'").