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.
Top comments (2)
Great tip! Thank you. Didnโt know this one.
Cool, glad you found it useful.