×

typescript · level 3 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

keeps your values exactly as you wrote them.

Write let size = "large"; and TypeScript labels the box string, not "large", because a let might change later. That is : an exact literal type grows into its general type. Object properties widen too, even inside a const object, because properties can change.

Add as const after a value and nothing widens. Strings stay literal types and numbers stay exact. Arrays become readonly tuples, and every property becomes readonly. Try to change one and the checker stops you with TS2540.

const loose = { size: "large", sugar: 2 };
const exact = { size: "large", sugar: 2 } as const;
loose.size = "tiny";
console.log(loose.size, exact.size);
const sizes = ["small", "medium", "large"] as const;
console.log(sizes.length, sizes[2]);

Think of as const as laminating a card: everyone can read it, nobody can write on it.