Loading lessons...
Readonly Properties & Index Signatures
Readonly Properties & Index Signatures
Interfaces support immutability rules and dynamic key definitions.
Readonly Properties
Mark properties with the readonly modifier to prevent reassignment after initialization.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 10, y: 20 };
// p.x = 15; // Error: Cannot assign to 'x' because it is a read-only property.
Index Signatures
When object keys are unknown in advance, use Index Signatures:
interface StringDictionary {
[key: string]: string;
}
const translations: StringDictionary = {
hello: "Hola",
goodbye: "Adiós",
thankYou: "Gracias"
};
TL;DR
readonlyfields can only be set when the object is created.- Index signatures allow defining objects with arbitrary key names matching a type pattern.