Skip to content

const assertion vs let: mutable vs readonly

Quick summary

You used 'let x = { a: 1 } as const' expecting immutability, but 'let' allows reassignment — only 'const' prevents it.

Why this happens

  • You used 'let' with 'as const' and expected the variable to be immutable, but let allows reassignment

  • An array declared with 'as const' using 'let' can be reassigned even though its elements are readonly

  • You confused 'const' (prevents reassignment) with 'as const' (narrows to literal types) — they serve different purposes

Minimal example

✗ Broken code
let config = { mode: 'production' } as const;
config = { mode: 'development' }; // allowed! let permits reassignment
// config.mode = 'test'; // error: readonly property
✓ Fixed code
const config = { mode: 'production' } as const;
// config = { mode: 'development' }; // error: cannot assign to 'config'
// config.mode = 'test'; // error: readonly property

Using 'const' prevents reassignment of the variable, while 'as const' makes the properties readonly and narrows to literal types.

How to diagnose

  • Try to reassign the variable — if it succeeds, the variable is not const even though the type is narrowed

  • Check whether the variable is declared with 'let' or 'const' — only 'const' prevents reassignment

  • Hover over the variable to see if the type is narrowed to literals (as const) but the binding is still mutable (let)

How to fix

  • Use 'const' instead of 'let' if the variable should not be reassigned: const x = { a: 1 } as const

  • Use 'let' without 'as const' if you need both reassignment and mutable types

  • Use Readonly<T> or ReadonlyArray<T> for readonly types without literal narrowing if you need let

How to prevent

  • Understand that 'as const' narrows types to literals but does not prevent reassignment — use 'const' for that

  • Use 'const' with 'as const' for immutable constants with literal types

Related Resources

Related Glossary

Related Lessons

← Back to language