Literal types and enums
A literal type is one exact value used as a type, and a union of them is a short list of allowed values. Watch tsc accept "left", reject the near miss "centre" and accept "center", then see an enum number its members 0, 1, 2, 3 and survive into the running JavaScript as a real object that prints 2 Left.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01A variable has type "left" | "right" | "center". Which value can it hold?
A union of literal types allows exactly its members, spelled exactly. "centre" and "Left" are different strings, so tsc rejects them.
02What type does TypeScript give s in: let s = "left";
A let can be given a new value later, so TypeScript widens it to string. With const c = "left" the type stays the literal "left", because a const can never change.
03In enum Dir { Up, Down, Left, Right }, what is the value of Dir.Left?
With no values written, the first member is 0 and each next member is one more: Up = 0, Down = 1, Left = 2, Right = 3.
04After tsc compiles align.ts, what is left of type Align and enum Dir in align.js?
Types are erased: the alias Align leaves nothing behind. A (non-const) enum is one of the few TypeScript features that produces JavaScript: an object filled with names and numbers.
05What does console.log(Dir.Left, Dir[2]) print?
Dir.Left looks up the name and gives 2. Numeric enums also get a reverse mapping, so Dir[2] gives "Left". console.log separates them with a space.
Glossary
- Literal type
- A type that is one exact value, such as "left" or 42. Only that value fits it.
- Union type
- Several types joined with |, read as "or". A value fits if it fits any one of them.
- Type alias
- A name for a type, written with type, like type Align = "left" | "right" | "center".
- Widening
- TypeScript giving a let variable a general type (string) instead of the literal it starts with, because it may change later.
- Enum
- A named set of constants, written with enum. Numeric members are numbered from 0 unless you give values.
- Reverse mapping
- In a numeric enum's object, the entry that goes from the number back to the name, so Dir[2] is "Left".
- Type erasure
- tsc removing types when it writes JavaScript. Enums are an exception: they become real objects.
Notes and sources
- The "Did you mean" part (error TS2820) is what tsc 5.9 adds when an allowed value is spelled almost the same. With no close match the error is TS2322 without the suggestion.
- The align.js shown is what tsc 5.9 writes with no settings; its default target writes let as var. Other targets change small details, not the enum object.
- Only numeric members get the number-to-name reverse mapping. String enums, such as enum Mode { On = "ON" }, map names to strings only.
- A const enum, or a union of literals, leaves no object behind: the values are put in directly. Many codebases prefer a literal union for that reason.
Quiz Unlocks after the last step.