Sub topic 4
Optional and readonly properties
Prerequisites
This chapter assumes basic TypeScript syntax, interfaces, object types, and compiler error messages. It also assumes strictNullChecks is enabled, as it is in the strict compiler option.
An optional property uses ?:
interface User {
name: string;
nickname?: string;
}
const user: User = { name: "Ada" };nickname?: string means that the property may be absent. When you read it, its value may be undefined:
function greet(user: User): string {
return user.nickname ?? user.name;
}The nullish coalescing operator, ??, uses the value on the right when the value on the left is null or undefined.
Assignability checks whether the source type provides every required property of the target type. A type with an optional property can receive a value that has that property or omits it. It cannot be assigned to a type where that property is required.
interface RequiredNickname {
name: string;
nickname: string;
}
const withNickname: User = {
name: "Ada",
nickname: "The programmer",
};
const required: RequiredNickname = withNickname;
// Error: nickname might be undefinedThe exactOptionalPropertyTypes compiler option makes an important distinction. Without it, TypeScript commonly allows this:
const first: User = { name: "Ada", nickname: undefined };With exactOptionalPropertyTypes: true, omission and explicit undefined are different. The declaration must include undefined if that value should be allowed:
interface UserWithUndefined {
name: string;
nickname?: string | undefined;
}Readonly properties
A readonly property cannot be changed through the type that declares it:
interface Point {
readonly x: number;
y: number;
}
const point: Point = { x: 1, y: 2 };
// point.x = 3; // Error
point.y = 3; // OKreadonly is a compile-time restriction. It does not freeze the object at runtime, and it is shallow. A nested object can still be changed unless its own properties are readonly.
Assigning a mutable object to a readonly view is useful when a function should inspect data without modifying it:
interface ReadonlyPoint {
readonly x: number;
readonly y: number;
}
function distanceFromOrigin(point: ReadonlyPoint): number {
return Math.hypot(point.x, point.y);
}
const coordinates = { x: 3, y: 4 };
const view: ReadonlyPoint = coordinates;
coordinates.x = 6; // The mutable variable can still change the objectThe readonly view protects the function’s code, not every reference to the object.
Exercise
Why does a value with an optional nickname fail when assigned to a type with a required nickname?
Show answer
The source may omit nickname or contain undefined, so it cannot guarantee the required property.