Sub topic 4
Optional properties and parameters
Prerequisites: you should know basic TypeScript types, interfaces, union types, and JavaScript’s null and undefined. This chapter assumes strictNullChecks is enabled.
An optional property is a property that an object may omit. Add ? after the property name:
interface User {
name: string;
middleName?: string;
}
const ada: User = { name: "Ada" };
const grace: User = { name: "Grace", middleName: "Brewster" };With strictNullChecks, reading middleName produces a string | undefined value. The property might not exist, so code must handle that possibility.
function formatName(user: User): string {
if (user.middleName === undefined) {
return user.name;
}
return `${user.name} ${user.middleName}`;
}
console.log(formatName(ada)); // Ada
console.log(formatName(grace)); // Grace BrewsterThe ? describes omission. It does not mean that the property can contain null. If null is also valid, write that explicitly:
interface Profile {
nickname?: string | null;
}Now a read from nickname can produce string | null | undefined.
Optional parameters
An optional parameter uses the same ? syntax. Its type includes undefined inside the function body:
function greet(name: string, punctuation?: string): string {
const ending = punctuation ?? ".";
return `Hello, ${name}${ending}`;
}
console.log(greet("Ada")); // Hello, Ada.
console.log(greet("Ada", "!")); // Hello, Ada!An optional parameter must come after required parameters. Callers may omit it or pass undefined:
greet("Ada");
greet("Ada", undefined);
greet("Ada", "!");A default parameter is another way to handle an omitted or undefined argument:
function connect(host: string, port = 443): string {
return `${host}:${port}`;
}
console.log(connect("example.com")); // example.com:443
console.log(connect("example.com", 8443)); // example.com:8443A default parameter is treated as optional when the function is called, but inside the function port has type number.
Optional properties versus required properties
Use an optional property when absence has meaning. Use a required property when every valid object must provide a value.
interface RequestOptions {
timeoutMs?: number;
retries: number;
}
function describe(options: RequestOptions): string {
const timeout = options.timeoutMs ?? 5000;
return `retries=${options.retries}, timeout=${timeout}ms`;
}
console.log(describe({ retries: 2 }));
console.log(describe({ retries: 2, timeoutMs: 1000 }));The retries property is required, so omitting it is an error. The timeoutMs property is optional, so the function supplies a fallback when it is absent.
Destructuring optional values
Destructuring does not remove the possibility of undefined. Give the value a default or narrow it before use:
interface Page {
title: string;
subtitle?: string;
}
function heading(page: Page): string {
const { title, subtitle = "Untitled section" } = page;
return subtitle === "" ? title : `${title}: ${subtitle}`;
}
console.log(heading({ title: "Setup" }));
console.log(heading({ title: "Setup", subtitle: "Install TypeScript" }));The default applies when subtitle is undefined, including when the property is omitted.
When an API returns optional data, handle it at the boundary. After a check, the rest of the function can work with a definite value:
function subtitleLength(page: Page): number {
if (page.subtitle === undefined) {
return 0;
}
return page.subtitle.length;
}Exercise
What is the type of options.timeoutMs when options has type RequestOptions, and why must a function handle that type?
Show answer
Its type is number | undefined because the optional property may be omitted. The function must provide a default, check for undefined, or pass the value to code that accepts undefined.