DEV Community

Carl Saunders
Carl Saunders

Posted on

๐Ÿ’ป๐Ÿ’จ Quick TypeScript - Make Object Literal Properties Read-only

Have you ever found yourself declaring a variable (for an object literal) using the const keyword and then assume those properties within that variable were read-only?

const person = {
  firstName: 'Carl',
  lastName: 'Saunders'
};
Enter fullscreen mode Exit fullscreen mode

In the above example most developers would assume the firstName and lastName properties cannot be changed and are read only. WRONG!

The below code is perfectly valid and can lead to bugs and these won't be caught until your code is production.

person.firstName = 'Joe'; // valid assignment, even though const was used
person.lastName = 'Bloggs'; // valid assignment, even though const was used
Enter fullscreen mode Exit fullscreen mode

Const Assertions (as const keyword)

TypeScript has built-in support for guarding against this and can be achieved by using the const assertions. Behind the scenes TypeScript is converting all those properties defined on the object literal into read-only versions.

const person = {
  firstName: 'Carl',
  lastName: 'Saunders'
} as const;
Enter fullscreen mode Exit fullscreen mode

Now if we tried to assign firstName property a new value the compiler would report the following error.

Cannot assign to 'firstName' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

Note: The const assertion as const feature is supported in TypeScript 3.4+. Also only works when you haven't already typed the object.

More Info

TypeScript Docs - Const Assertions

Top comments (2)

Collapse
 
khrome83 profile image
Zane Milakovic

Great tip! Thank you. Didnโ€™t know this one.

Collapse
 
deadlybyte profile image
Carl Saunders

Cool, glad you found it useful.