Read-only API views
Expose configuration or domain data without allowing callers to reassign its properties.
TypeScript · Type Alias
Readonly<Type> creates a type whose properties cannot be reassigned by TypeScript. It is useful for describing frozen or otherwise read-only object views.
Readonly<Type> creates a mapped type whose properties correspond to Type but are marked readonly. TypeScript therefore rejects assignments to those properties, making the type useful for values such as frozen objects; this restriction applies during type-checking rather than enforcing runtime immutability.
Readonly<Type>| Name | Type | Description |
|---|---|---|
Type | Type | The source object type whose properties become readonly. |
A type with all properties of Type marked readonly.
interface Todo {
title: string;
completed: boolean;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
completed: false,
};
// TypeScript error: cannot assign to a readonly property.
todo.title = "Archive inactive users";Readonly<Todo> prevents assignments to Todo's properties during type-checking.
Expose configuration or domain data without allowing callers to reassign its properties.
Describe the return type of a generic helper that freezes an object.
Model an existing value whose fields should be treated as non-writable by consumers.
Readonly<Type> constructs a type with every property of Type marked readonly. Assignments to those properties are rejected by the type checker.
Follow-up: How would you type a freezing helper? Use a generic signature such as function freeze<Type>(obj: Type): Readonly<Type>;.
It is useful when modeling an object whose properties cannot be reassigned, including the result type of a frozen-object helper. The restriction is represented statically by the readonly properties.
Follow-up: What does it not guarantee? It does not by itself perform the runtime operation that freezes the object.
The utility was released in TypeScript 2.1. Its behavior is expressed through a mapped type that applies readonly to each property in the input type.
Follow-up: What related array type should be considered? ReadonlyArray<T> is the dedicated type for arrays that should not be mutated.
PartialRecordPickReadonlyArray