Typescript const assertions

TypeScript 27-11-2023

const declaration A const declaration makes the array reference immutable.

const myValues = ['one', 'two', 'three'];

// Values can still added and removed
myValues.pop();
myValues.push('next');

// reassignment isn't possible anymore
// TS2588: Cannot assign to 'myValue' because it is a constant.
myValues = ['new', 'array'];

const assertion With a const assertion, the array reference and the array values are immutable.

const myValues = ['one', 'two', 'three'] as const;

// Values can't be added and removed
// TS2339: Property 'pop' and property 'push' does not exist on type 'readonly
myValues.pop();
myValues.push('next');

// reassignment isn't possible anymore
// TS2588: Cannot assign to 'myValue' because it is a constant.
myValues = ['new', 'array'];

Important! The array is not immutable at runtime. Everything with as const is just at write time immutable.