TypeScript Readonly Utility Type
`Readonly< T >` makes all properties of an object immutable. This prevents accidental modifications and helps write safer code.
Basic Readonly Usage
type User = {
id: number;
name: string;
};
const user: Readonly<User> = {
id: 1,
name: "Alice"
};
user.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property.
When a `user` object is defined as `Readonly< User >`, its properties become read-only and TypeScript raises errors on modification attempts.
Using Readonly in Function Parameters
type Config = {
apiUrl: string;
timeout: number;
};
function freezeConfig(config: Readonly<Config>) {
// config.timeout = 5000; // Error!
console.log("Config is locked:", config);
}
freezeConfig({ apiUrl: "https://api.example.com", timeout: 3000 });
// Output: Config is locked: { apiUrl: "https://api.example.com", timeout: 3000 }
`Readonly` is useful for objects like configuration (`config`) that should not be modified inside functions, clearly expressing intent.
Practical Example: Todo List
type Todo = {
title: string;
completed: boolean;
};
const todo: Readonly<Todo> = {
title: "Learn TypeScript",
completed: false
};
console.log(todo);
// Output: { title: "Learn TypeScript", completed: false }
Defining `Readonly< Todo >` ensures a todo item remains unchanged and can be safely shared across the app.
When to Use Readonly?
`Readonly` is ideal for `props`, `config`, `constants`, or any values that must remain unchanged. It works at compile time, similar to `freeze` but safer.
Back