Sub topic 3
Writing nullable types with unions
Assume you know basic TypeScript types, interfaces, union types, and tsconfig.json. This chapter also assumes strictNullChecks is enabled. With this option, TypeScript treats missing values as part of the type system instead of allowing them everywhere.
A nullable type is a union
A union type allows a value to have one of several types. Write the alternatives with the | operator:
let displayName: string | null;
displayName = "Ada";
displayName = null;
// displayName = 42; // Error: number is not assignableThe type string | null means “either a string or the value null.” The variable must always contain one of those two values.
You can also include undefined:
let result: string | undefined;
result = "success";
result = undefined;This type commonly represents a value that has not been provided or cannot be found.
null and undefined are different JavaScript values. Many programs use null to represent an intentional empty value and undefined for a missing value. TypeScript does not guess that they are interchangeable:
| Type | Accepted values | Column | Column |
|---|---|---|---|
| `string` | Strings only | ||
| `string \ | null` | Strings or `null` | |
| `string \ | undefined` | Strings or `undefined` | |
| `string \ | null \ | undefined` | Strings, `null`, or `undefined` |
Nullable function inputs and outputs
Union types describe the contract at function boundaries. A parameter typed string | null requires the caller to handle the possibility of null:
function formatName(name: string | null): string {
if (name === null) {
return "Anonymous";
}
return name.toUpperCase();
}
console.log(formatName("Ada")); // ADA
console.log(formatName(null)); // AnonymousThe return type is simply string because every path returns a string. If a function can return no result, include that possibility in its return type:
function findInitial(name: string): string | undefined {
if (name.length === 0) {
return undefined;
}
return name[0];
}
console.log(findInitial("Ada")); // AA common error is declaring a function as returning only string while returning undefined on one path:
function findInitialWrong(name: string): string {
if (name.length === 0) {
return undefined; // Error
}
return name[0];
}The error is useful. It identifies a mismatch between the function's promise and its implementation. Either return a fallback string or change the return type to string | undefined.
Choose the union that matches the boundary
Do not add every missing-value type automatically. Model what the actual API produces.
type UserId = string | number;
function labelForId(id: UserId | null): string {
if (id === null) {
return "No user";
}
return `User ${id}`;
}Here, UserId describes valid identifiers, while null describes the separate possibility that no identifier exists. Keeping those meanings visible makes later checks easier to understand.
A union does not remove the need for runtime checks. Before using a value as a string, prove that it is a string or handle the other alternatives.
Exercise
What is the correct return type for a function that returns a number when it succeeds and undefined when no number exists?
Show answer
number | undefined.