ยท new features
How to use const assertions in TypeScript
TypeScript 3.4 introduced const assertions, which allow you to claim a value as immutable. This is useful when working with arrays, as it prevents new values from being added to an existing array.
TypeScript 3.4 introduced const assertions, a feature that allows you to claim a value as immutable. This feature is particularly valuable in combination with array literals, as it prevents new values from being pushed into an existing array.
Contents
- const declarations
- const assertions
- Important note
- Best Practice
- as const with objects
- as const with strings
- Alternative Options
- Video Tutorial
const declarations
A const declaration only makes the array reference immutable.
Example
const assertions
With a const assertion you will get immutability for your array reference and array values at design-time.
Example
Important note
One important thing to note is that const assertions are a TypeScript feature at design-time and do not actually make values immutable at runtime. This means that you will still be able to modify values at runtime using plain JavaScript. If you want to achieve a higher level of immutability, you can make use the Object.freeze() API.
Example
Best Practice
You can combine a const assertion with Object.freeze
to get type safety at design-time and runtime:
as const with objects
A const assertion can also protect an object literal by marking its properties as readonly
:
as const with strings
You can narrow the type for a string to a specific string using as const
:
Alternative Options
You can use the ReadonlyArray
type of TypeScript 3.4 to disallow array value modifications at design-time:
Example
Shorthand Syntax