Object types, unions, and narrowing
7.0.2
Use object types to describe fields and unions to express more than one valid shape.
On this page
Required and optional fields
An interface or type alias can describe an object’s fields. A trailing question mark marks a field as optional. With strict null checks, handle the missing value before you use it as a string.
interface Product {
name: string;
price: number;
label?: string;
}
function displayName(product: Product) {
return product.label ?? product.name;
}
Narrow with a check
Use typeof, equality, or a shared literal field to narrow a union. In the example, checking ok lets the compiler determine which fields exist in each branch.
type Result =
| { ok: true; total: number }
| { ok: false; message: string };
function describe(result: Result) {
if (result.ok) return "Total: " + result.total;
return result.message;
}