TypeScript Reference ยท Concepts and Comparisons
null and undefined in TypeScript
How TypeScript treats null and undefined: strictNullChecks, optional values, ?? and ?., narrowing, and a clear convention for absence.
JavaScript has two "nothing" values. undefined is what the language gives you when something is missing: an uninitialized variable, an absent property, a function with no return. null is a value you put there on purpose to mean "no value".
With strictNullChecks on (part of strict), TypeScript treats both as separate types that are not part of string, number or object types. You must say string | null when absence is allowed, and the compiler then makes you handle it. This removes a large class of "cannot read properties of undefined" crashes.
let name: string | undefined; // name.length; // error TS18048: 'name' is possibly 'undefined'.
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.
Practical differences
undefined |
null |
|
|---|---|---|
| Produced by | The language (missing property, unset variable, no return) | Code and APIs (JSON, DOM getElementById) |
typeof |
"undefined" |
"object" (a historic quirk) |
| Default parameter applies | Yes | No |
Dropped by JSON.stringify in objects |
Yes | Kept as null |
| Loose equality | undefined == null is true |
same |
Usage notes
- Use
x == nullonly when you deliberately want to catch both; otherwise compare strictly. TypeScript narrowsx == nulltonull | undefinedin the true branch. - Optional (
?) is not the same as| undefined. WithexactOptionalPropertyTypesan optional property may be absent but not explicitlyundefined; see exactOptionalPropertyTypes. - Non-null assertion
!removes both from the type without checking. Use it only where an invariant guarantees presence; see Non-null assertion. - Pick a convention. Many codebases use
undefinedfor "not provided" andnullonly for external data that already uses it. - Arrays and maps:
array[i]andrecord[key]are notundefined-aware unless you enable noUncheckedIndexedAccess;Map.getalways includesundefined. - Without
strictNullChecks, both values are assignable to every type, and the compiler cannot protect you. - Return types: a function that may find nothing should say so in its signature, such as
T | undefined.