Use Const Assertions in TypeScript to enforce readonly properties of literal expressions
Thursday, July 9, 2020
Use Const Assertions in TypeScript to enforce readonly properties of literal expressions
Introduced in TypeScript version 3.4, const
assertions provide the ability to enforce readonly
properties of literal expressions.
Let's break that down:
- Defining a new
array
orobject
literal using theconst
modifier enforces that the variable isreadonly
. - However, the members of the array or object are not
readonly
. - Further, the member types can be "widened"; meaning that a literal expression whose member value is 'Brian' can be widened to the type
string
.
So, how do we use const
assertions with literal expressions? Let's take a look at an object literal expression:
const user = {
firstName: 'Brian',
lastName: 'Love'
} as const;
Note the use of the as const
assertion following the object literal expression. This asserts that the members of the user
property are readonly
.
Here is an example of using const
assertions for a tuple literal expression:
const defaultConfig = [PaymentMethod.Card, true] as const;
Again, take note of the use of the as const
assertion following the tuple literal expression.
You can learn more about const
assertions in the TypeScript 3.4 release notes.
Instructions
Using const assertions to enforce readonly properties of literal expressions
Code Examples
use const
assertion for object literals
const user = {
firstName: 'Brian',
lastName: 'Love'
} as const;
user.firstName = 'Bonnie'; // 🛑 Cannot assign to 'firstName' because it is a read-only property.
use const
assertions for tuple literals
enum PaymentMethod {
Card,
Cash,
Points
}
const defaultConfig = [PaymentMethod.Card, true] as const;
defaultConfig[0] = PaymentMethod.Cash; // 🛑 Cannot assign to '0' because it is a read-only property.
mutation of object literal expression members
const user = {
firstName: 'Brian',
lastName: 'Love'
};
user.firstName = 'Bonnie'; // ⚠️ firstName property is not readonly
mutation of tuple literal expression members
enum PaymentMethod {
Card,
Cash,
Points
}
const defaultConfig = [PaymentMethod.Card, true];
defaultConfig[0] = PaymentMethod.Cash; // ⚠️ The default config is accidentally changed because the first member of the tuple is not readonly
Have a question or comment?