Making All Properties Readonly
What you'll learn: How to use the readonly modifier in mapped types to transform every property of an object into a read-only version, creating compile-time immutable objects.
The Core Idea
You've already seen the readonly modifier on individual properties. Now imagine applying it to every property in an object type automatically. That's what a mapped type can do.
Just like you created a mapped type that makes all properties optional with ?, you can add the readonly modifier in the exact same position to make all properties read-only:
type ReadonlyVersion<T> = {
readonly [K in keyof T]: T[K];
};
This pattern iterates over every key K in type T, preserves the original type T[K], but adds readonly before the property name.
Using the readonly Modifier
type User = {
id: number;
name: string;
email: string;
};
type ImmutableUser = {
readonly [K in keyof User]: User[K];
};
const user: ImmutableUser = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
// ❌ Error: Cannot assign to 'name' because it is a read-only property
user.name = "Bob";
Every property becomes read-only at compile time, preventing accidental mutations.
A Generic Readonly Mapper
Make it reusable with generics:
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
type Product = {
sku: string;
price: number;
};
const item: MyReadonly<Product> = {
sku: "ABC123",
price: 29.99
};
// ❌ Error: Cannot assign to 'price'
item.price = 19.99;
This is precisely how TypeScript's built-in Readonly<T> utility works under the hood.
Key Takeaway:
Adding the readonly modifier inside a mapped type creates an immutable version of any object type, preventing property reassignment at compile time—perfect for enforcing immutability patterns in your codebase.