💻💨 Quick TypeScript - Make Object Literal Properties Read-only

Carl Saunders - Jan 29 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . .