Lesson 2 · Unit 03
Literal Types at Work
as const, template literal types, satisfies, and unions against enums
What you practise
as const, template literal types,satisfies, unions of literals against enums
Try a question from this lesson
Pick one
Line 2 asks for the type of an element of routes. The real routes are right there on line 1, so is the typo on line 3 caught?
const routes = ["/home", "/about"];
type Route = (typeof routes)[number];
const r: Route = "/hmoe";Correct answer
No: Route is just string
Why
The compiler inferred string[] for routes, because an array can be pushed to and its elements replaced. "The type of an element" is therefore plain string, and every typo fits. The literals were forgotten on line 1.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
as const
as const tells the compiler to infer the narrowest type it can: every string and number keeps its literal type, arrays become readonly tuples and properties become readonly.
Now the value can drive the types. (typeof routes)[number] is the union of the actual elements. The list is written once, and both the run-time code and the type follow it.
const routes = ["/", "/about"] as const;
// readonly ["/", "/about"]
type Route = (typeof routes)[number];
// "/" | "/about"
const ok: Route = "/about";Concept
Template literal types
A template literal type builds string types the way a template string builds strings. Put a union in a slot and you get every combination.
Python's f-strings exist only at run time. Here the compiler knows the full set of strings a value may be, and rejects the rest. Helpers such as Capitalize change the text of a literal type.
type Size = "sm" | "lg";
type Cls = `btn-${Size}`;
// "btn-sm" | "btn-lg"
const a: Cls = "btn-lg";
// const b: Cls = "btn-xl"; // rejected
type Handler = `on${Capitalize<"click">}`;
// "onClick"Concept
satisfies
An annotation checks a value and then replaces its type with the annotation: the details are forgotten. satisfies checks the value against a type and keeps the type that was inferred.
Use it when you want both "this object must fit the shape" and "remember exactly what I wrote".
type Val = string | number;
type Theme = Record<string, Val>;
const t = {
gap: 8,
ink: "#222",
} satisfies Theme;
t.gap.toFixed(1); // gap is a number
t.ink.toUpperCase(); // ink is a string9 more exercises in the app
- 3× multiple choice
- 1× match the pairs
- 2× type the answer
- 2× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.