Utility Type Readonly in TypeScript
Readonly is a utility type in TypeScript that makes all type properties read-only. After a property becomes readonly, it cannot be changed through direct assignment in code, which helps avoid unintentional object mutations.
Syntax
Readonly<T>
T— original type whose properties you want to make immutable.
The Readonly type is most often used to protect objects from unwanted changes while maintaining read access to their properties.
When to use Readonly?
- If object shouldn't change after creation.
- For working with constant objects.
- When passing data to function to avoid accidental changes.
Readonly Usage Example
- Creating object with immutable properties:
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = {
id: 1,
name: "Alice",
};
user.name = "Bob";
// Error: Cannot assign to 'name' because it is a read-only property`
- Here
ReadonlyUserturns all properties (idandname) intoreadonly. - Attempting to change any property leads to compilation error.
Example for immutable configurations:
Sometimes you need to fix settings so they can't be changed after initialization:
interface Config {
readonly port: number; // Already explicitly set
dbName: string;
}
// Using Readonly makes all fields read-only
type FullReadonlyConfig = Readonly<Config>;
const config: FullReadonlyConfig = {
port: 8080,
dbName: "mainDB",
};
config.dbName = "testDB";
// Error: 'dbName' is read-only`
- Field
porthasreadonly, but alsodbNamebecomesreadonlywhen we wrap entire interface inReadonly<Config>.
Using in functions
- Guaranteeing argument immutability
Can declare function parameters asReadonly<T>to prevent accidental changes to passed object:
function printUser(user: Readonly<User>) {
// user.id = 42; // Error
console.log(user.id, user.name);
}
- This protects from object mutations inside function.
Summary
- Readonly is a convenient way to protect object properties from changes.
- Applied when you want to explicitly indicate object should remain unchanged throughout usage.
- When attempting to assign anything to
readonlyproperty, TypeScript will throw error at compilation stage, helping avoid unintentional mutations.