Readonly mapped type
- TypeScript course
- Intermediate
- Lesson 33/89
- 4 min
Learn to make all properties readonly with a mapped type.
Readonly mapped type
With a mapped type you can make all of T's properties readonly. Writing { readonly [K in keyof T]: T[K] } makes each property immutable; the value type stays the same. This is exactly what TypeScript's built-in Readonly utility type does.
type Sabit<T> = {
readonly [K in keyof T]: T[K];
};
interface Nokta { x: number; y: number; }
const n: Sabit<Nokta> = { x: 3, y: 5 };
// n.x = 10; // compile errorThe immutability guarantee
A readonly mapped type gives compile-time immutability. If an object is of type Sabit<T>, its properties cannot be reassigned. This prevents accidental modification, especially in configuration or constant data structures. It has no runtime effect; only the compiler enforces it.
Practice Immutable point
Write the mapped type Sabit<T> as { readonly [K in keyof T]: T[K] }. Define interface Nokta with x: number and y: number. Define type SabitNokta as Sabit<Nokta>. Assign { x: 3, y: 5 } to a variable n (of type SabitNokta). Print n.x with console.log.
Starter code
// Sabit<T> mapped type tanımla
// T'nin tüm özelliklerini readonly yap, değer türü aynı kalsın
// Nokta arayüzünü x ve y ile tanımla
// SabitNokta türünü Sabit<Nokta> olarak tanımla
// n değişkenine nokta nesnesini ata
// x değerini yazdırSample solution
type Sabit<T> = {
readonly [K in keyof T]: T[K];
};
interface Nokta {
x: number;
y: number;
}
type SabitNokta = Sabit<Nokta>;
const n: SabitNokta = { x: 3, y: 5 };
console.log(n.x);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What changes for an object produced by the mapped type below?
type Sabit<T> = { readonly [K in keyof T]: T[K]; };- The value types change
- The property names change
- The properties become immutable Correct answer
- The properties become optional
Explanation: Adding readonly prevents properties from being modified; value types and names stay the same. Changing types is done via the right side; making optional is done with ?.
2 Add readonly
type Sabit<T> = {
____ [K in keyof T]: T[K];
};
type Sabit<T> = {
readonly [K in keyof T]: T[K];
};
Explanation: To make all properties immutable in a mapped type you use readonly. optional is not a valid keyword; const is for variables; static is for class members.
3 Readonly mapped type parts
| Term | Meaning |
|---|---|
readonly [K in keyof T] |
Makes all properties immutable |
T[K] |
Keeps the value type the same |
n.x = 10 |
Gives a compile error |
type Sabit<T> |
Readonly mapped type alias |