Sub topic 3
Writing nullable types with unions
This chapter assumes you know basic TypeScript types, union types and type annotations, the difference between JavaScript's null and undefined, and how to turn on strictNullChecks in tsconfig.json. The earlier chapters covered those. Here you will learn how to write the types that describe "this value might be missing".
Why unions carry the "missing" case
With strictNullChecks on, null and undefined are their own types. They are not hidden members of every other type. A variable typed string can only hold strings.
A value that may be missing therefore needs a type that says so. TypeScript uses a union type for this: string | null means "a string, or null". There is no special nullable syntax such as string?. Nullable types are ordinary unions, so everything you know about unions applies to them.
Without strictNullChecks, the compiler treats null and undefined as assignable to every type. A union such as string | null then collapses to plain string, and the compiler cannot warn you about missing values. This is why the flag matters.
The three common shapes
You will meet three shapes in real code.
| Type | Meaning | Typical source | Column | Column |
|---|---|---|---|---|
| `T \ | null` | A value was looked up or computed, and the answer is "nothing" | JSON from an API, `document.querySelector`, a database row | |
| `T \ | undefined` | The value was never provided or never found | Optional parameters, `Array.prototype.find`, `Map.get` | |
| `T \ | null \ | undefined` | Either of the above may happen | Input from code you do not control |
The following example shows all three and what the compiler accepts:
let id: number | null = null;
id = 42;
id = null;
// id = undefined; // Error: Type 'undefined' is not assignable to type 'number | null'.
let nickname: string | undefined;
nickname = "ada";
nickname = undefined;
// nickname = null; // Error: Type 'null' is not assignable to type 'string | undefined'.
let anything: string | null | undefined = null;
anything = undefined;
anything = "ok";null and undefined are not interchangeable in a union. If you declare number | null, assigning undefined is an error. That precision is useful, because it forces you to be consistent about which "no value" a given API uses.
A variable declared with let nickname: string | undefined; and no initializer starts as undefined, which its type allows. A let name: string; with no initializer produces a "used before being assigned" error if you read it too early.
Where nullable unions appear
You can place a nullable union anywhere a type is allowed.
interface User {
id: number;
name: string;
email: string | null; // the key is always present, the value may be null
}
function findUser(users: User[], id: number): User | undefined {
return users.find((u) => u.id === id);
}
const users: User[] = [
{ id: 1, name: "Ada", email: "[email protected]" },
{ id: 2, name: "Grace", email: null },
];
const user = findUser(users, 2);
// console.log(user.name); // Error: 'user' is possibly 'undefined'.
if (user !== undefined) {
console.log(user.name); // OK: narrowed to User
}Three places deserve attention:
- Properties.
email: string | nullmeans the property must exist, but its value may benull. This differs from an optional propertyemail?: string, which can be left out entirely. The next chapter covers that difference. - Return types. A function that may not find or produce a result should say so in its return type.
User | undefinedtells every caller that they must handle the missing case. - Parameters.
function greet(name: string | null)forces callers to pass an argument, even if it isnull. An optional parameter (name?: string) lets them omit it.
What you can do with a union before narrowing
A union type only allows operations that are valid for every member. null and undefined have no properties, so almost nothing is valid on a nullable value until you rule them out.
function length(s: string | null): number {
return s.length; // Error: 's' is possibly 'null'.
}The error text names the exact problem. Current TypeScript versions report:
's' is possibly 'null'.(TS18047)'s' is possibly 'undefined'.(TS18048)'s' is possibly 'null' or 'undefined'.(TS18049)
Older versions (before TypeScript 4.9 or so) use the less specific Object is possibly 'null'. (TS2531). Both mean the same thing: you used the value as if it were present, and the type does not guarantee that.
The compiler does allow a few things on a nullable value without narrowing, such as passing it to another function that accepts the same union, comparing it with ===, or returning it.
function pass(s: string | null): string | null {
return s; // fine: no property access
}The compiler does not make you handle the nullable case immediately. It makes you handle it before you use the value in a way that needs it.
How the compiler sees a nullable value
The following diagram shows how a value of type string | null | undefined splits into cases. Narrowing, covered in a later chapter, is the act of choosing a branch.
Placing the parentheses and the bar
Because | is an ordinary type operator, where you place it changes the meaning. Three cases cause real bugs.
Arrays. These two types are different:
let a: (string | null)[] = ["x", null]; // an array whose items may be null
let b: string[] | null = null; // the whole array may be null
b = ["x", "y"];(string | null)[] is always an array, but you must check each item. string[] | null may be missing entirely, but if present, every item is a string.
Function types. The | has lower precedence than =>, so you need parentheses:
type Callback = (() => void) | null; // the callback itself may be null
type Result = () => string | null; // a function that returns string or null
let cb: Callback = null;
cb = () => console.log("called");Without the parentheses, () => void | null is a function returning void | null, which is probably not what you meant.
Object properties. { name: string | null } is a property that holds a nullable string. { name?: string } is an optional property. They are not the same type.
A reusable alias
If you write T | null often, an alias keeps the intent visible. Generic aliases work like any other:
type Nullable<T> = T | null;
type Maybe<T> = T | null | undefined;
function parsePort(raw: string): Nullable<number> {
const n = Number(raw);
return Number.isInteger(n) && n > 0 && n < 65536 ? n : null;
}
const port: Maybe<number> = parsePort("8080");Do not overuse these. A reader who sees string | null knows exactly what it means. Maybe<string> makes them look up a definition. Use an alias when it names a project convention, and write the union out when it appears once or twice.
Choosing between null and undefined
The compiler does not force a choice, but your codebase should have a convention. A common and practical rule:
- Use
undefinedfor "not provided" or "not found", which matches what the language itself produces (Map.get,find, missing properties, omitted arguments). - Use
nullfor "deliberately empty", such as a field that exists but has no value, or when you read data from a source that usesnull(JSON, SQL). - Avoid mixing both in the same API. A function that returns
string | null | undefinedmakes every caller handle two cases that mean the same thing.
Pick one per API and convert at the boundary. For example, if your data layer returns null and your internal code prefers undefined, convert once, near the boundary, rather than carrying both through the program.
Common errors
- Forgetting that
undefinedis notnull. Assigning the result offind(which givesundefined) to a variable typedUser | nullfails. Change the type or convert the value. - Annotating a variable too narrowly.
let current = null;gives the variable a type that is too narrow for later assignments. Writelet current: User | null = null;. - Assuming
voidmeansundefined. A function returningvoidand a function returningundefinedare not the same type. If you want callers to be able to use a missing result as a value, writeundefinedin the return type. - Putting the bar in the wrong place. See the array and function examples above. When in doubt, add parentheses.
Putting it together
This complete program combines a nullable return, a nullable property, and a nullable alias. Save it as nullable.ts and compile it with tsc --strict nullable.ts.
type Nullable<T> = T | null;
interface Account {
owner: string;
nickname: Nullable<string>;
}
const accounts: Account[] = [
{ owner: "ada", nickname: "A" },
{ owner: "grace", nickname: null },
];
function lookup(owner: string): Account | undefined {
return accounts.find((a) => a.owner === owner);
}
function displayName(owner: string): string {
const account = lookup(owner);
if (account === undefined) {
return "unknown account";
}
if (account.nickname === null) {
return account.owner;
}
return account.nickname;
}
console.log(displayName("ada"));
console.log(displayName("grace"));
console.log(displayName("alan"));The function handles two different kinds of absence. undefined means the account does not exist, and null means the account exists but has no nickname. Each check removes one member of a union, and the compiler tracks the result.
Exercise
What is the difference between the types (number | null)[] and number[] | null? Give one value that is valid for the first type but not the second.
Show answer
(number | null)[] is always an array, and each item may be null. number[] | null may be null as a whole, but a non-null value must be an array of numbers only. The value [1, null, 3] is valid for the first type but not the second, because the second type does not allow null items.
Exercise
The following function does not compile under strictNullChecks. Fix the return type so it compiles without changing the body, and say which kind of missing value callers must now expect. function first(items: string[]): string { return items.find((s) => s.length > 0); }
Show answer
Change the return type to string | undefined. Array.prototype.find returns undefined when no item matches, so callers must now handle undefined, not null.