Lesson 1.3

Literal types and const assertions

By default a literal assigned to a mutable binding widens to its base type, because the binding could later hold any string.

6mIntermediate22.6k students

Overview

Widening, and how to stop it

By default a literal assigned to a mutable binding widens to its base type, because the binding could later hold any string. That is usually what you want and occasionally exactly what you do not.

A const assertion stops the widening: properties become readonly, arrays become tuples, and every literal keeps its exact type. It is the standard way to define a set of allowed values once and use it in both worlds.

From such an array you can derive the union of its members, so the runtime list and the type stay in sync automatically. Adding a value in one place updates both.

In this lesson you will:

  • Keep a literal from widening to string
  • Freeze an object or array into exact types
  • Derive a union from a runtime array

Resources

Previous Lesson
Next Lesson
Literal types and const assertions — TypeScript Deep Dive — Vertex