The readonly
modifier in TypeScript makes a property of an object read-only, meaning its value cannot be changed after initialization. It's useful for creating types of objects that shouldn't be modified after they're created. Example:
interface Person { readonly name: string; age: number; } const person: Person = { name: 'John', age: 25 }; person.name = 'Mike'; // Error! 'name' is read-only.
The const
keyword, on the other hand, is used for variables, indicating that the variable itself cannot be reassigned. However, the value assigned to a const
variable can still be modified if it is an object or array.
const person = { name: 'John', age: 25 }; person.age = 30; // OK, but person cannot be reassigned.
In summary: readonly
is used for object properties, while const
is used for variables.