Table of contents
- 1. const declarations
- 2. const assertions
- 3. Important note
- 4. Best Practice
- 5. as const with objects
- 6. as const with strings
- 7. Alternative Options
- 8. Video Tutorial
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.
A const declaration only makes the array reference immutable.
With a const assertion you will get immutability for your array reference and array values at design-time.
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
as const with strings
You can narrow the type for a string to a specific string using
You can use the
ReadonlyArray type of TypeScript 3.4 to disallow array value modifications at design-time: