Utility Types - Readonly
In this page:
Basic Readonly
Readonly<T> produces a version of an object type whose properties can no longer be reassigned, giving the same compile-time protection as writing the readonly modifier on every property by hand.
Example: Basic Readonly
interface Point {
x: number;
y: number;
}
const p: Readonly<Point> = { x: 1, y: 2 };
console.log(p);
Readonly Arrays
Readonly can also be applied to array types to prevent mutation through methods such as push, pop, or splice, while still allowing the array's existing elements to be freely read.
Example: Readonly Arrays
const values: ReadonlyArray<number> = [1, 2, 3];
console.log(values[0]);
Readonly Objects
Readonly is useful for objects that should be treated as fixed configuration or reference data — values that are meant to be read throughout the program's lifetime but never modified after creation.
Example: Readonly Objects
interface AppConfig {
apiUrl: string;
}
const config: Readonly<AppConfig> = { apiUrl: "https://api.example.com" };
console.log(config.apiUrl);
Readonly and Nested Objects
Readonly only applies to the top-level properties of an object; any nested objects inside it need their own separate Readonly wrapping if you want their properties protected too.
Example: Readonly and Nested Objects
interface Address {
city: string;
}
interface Person {
name: string;
address: Address;
}
const p: Readonly<Person> = { name: "Ravi", address: { city: "Patna" } };
p.address.city = "Delhi";
console.log(p.address.city);
When to Use Readonly
Readonly<T> is useful whenever callers should be able to inspect data freely but should never be able to reassign its properties, which helps prevent accidental shared-state bugs.
Example: When to Use Readonly
interface Constants {
PI: number;
}
const MATH: Readonly<Constants> = { PI: 3.14159 };
console.log(MATH.PI);
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates