1.

How to make object properties immutable in TypeScript? (hint: readonly)

Answer»

You can mark object properties as immutable by using the readonly keyword before the property NAME. For example:

interface Coordinate {readonly x: NUMBER;readonly y: number;}

When you mark a property as readonly, it can only be set when you initialize the object. Once the object is created, you cannot change it. 

let c: Coordinate = { x: 5, y: 15 };c.x = 20; // Cannot assign to 'x' because it is a read-only property.(2540)


Discussion

No Comment Found