How to declare a type as nullable in TypeScript?
To make a type nullable in TypeScript, union it with null
(and/or undefined
if desired). For example:
type MaybeString = string | null;
Now, MaybeString
can hold either a string or null
. If you want to account for undefined
too, do:
type MaybeString = string | null | undefined;
Details
-
Union with
null
let value: string | null = null; value = "Hello"; // also valid
-
Union with
undefined
If you want to allow the variable to beundefined
, add it to the union:let anotherValue: string | null | undefined; anotherValue = "World!"; anotherValue = undefined;
-
Optional Properties
If you’re marking properties as optional in interfaces or type definitions, you can use the?
syntax, which implicitly makes themtype | undefined
:interface Person { name: string; nickname?: string; // string | undefined }
-
Strict Null Checks
- In
tsconfig.json
,strictNullChecks
should be true to distinguish betweennull
andundefined
. - With strict null checks enabled, you can’t assign
null
orundefined
to a non-nullable type.
- In
If you want to strengthen your JavaScript knowledge (which underpins TypeScript), consider Grokking JavaScript Fundamentals by DesignGurus.io. It covers core topics like prototypes, closures, and async patterns—helping you better understand TypeScript’s typing of null
/undefined
and other advanced features.