loading...

πŸ’»πŸ’¨ Quick TypeScript - Make Object Literal Properties Read-only

deadlybyte profile image deadlybyte ・1 min read

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'
};

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

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;

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.

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

Posted on by:

deadlybyte profile

deadlybyte

@deadlybyte

I'm a full stack software developer specialising in React. With 20+ years’ experience, I'm passionate about following best practices and standards.

Discussion

markdown guide
 

Great tip! Thank you. Didn’t know this one.

 

Cool, glad you found it useful.