- Published on
Readonly type in TypeScript
- Authors

- Name
- Sif Mcarby
What is Readonly<T> in TypeScript?
Readonly<T> is a TypeScript utility type that makes all properties of a type immutable. Once a property is set, it cannot be changed.
How Does Readonly<T> Work?
It works like this:
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
This means each property in the type becomes read-only.
Example: Basic Usage
interface User {
id: number;
name: string;
email: string;
}
const getUser = (user: Readonly<User>) => {
console.log(`User:`, user);
// Uncommenting the next line will cause a TypeScript error
// user.name = 'New Name';
};
const user: Readonly<User> = { id: 1, name: 'Alice', email: 'alice@example.com' };
getUser(user);
In this example, the Readonly<User> type ensures that the user object cannot be modified.
Real-Life Example: Configuration Objects
Configuration objects are often read-only to prevent accidental changes.
interface Config {
apiUrl: string;
timeout: number;
}
const config: Readonly<Config> = {
apiUrl: 'https://api.example.com',
timeout: 5000,
};
function useConfig(config: Readonly<Config>) {
console.log(`Using API: ${config.apiUrl} with timeout: ${config.timeout}`);
// Uncommenting the next line will cause a TypeScript error
// config.timeout = 3000;
}
useConfig(config);
Here, the Readonly<Config> type ensures the config object cannot be altered after its creation.
Why Use Readonly<T>?
- Immutability: Protects objects from accidental changes.
- Safety: Ensures critical data remains consistent.
- Best Practices: Encourages immutable patterns in your code.
Example: Readonly Arrays
You can use ReadonlyArray<T> to prevent array modifications:
const numbers: ReadonlyArray<number> = [1, 2, 3];
// Uncommenting the next line will cause a TypeScript error
// numbers.push(4);
console.log(numbers);
This ensures that the array remains unchanged.
Readonly<T> is a powerful tool to enforce immutability, making your code safer and easier to understand. Use it when you need to protect objects or data from being modified.