14. What does the readonly modifier do, and how does it differ from const?

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.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.