1

Use Const Assertions in TypeScript to enforce readonly properties of literal expressions

Thursday, July 9, 2020

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 or object literal using the const modifier enforces that the variable is readonly.
  • 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

Consider

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
Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️