Sub topic 1
Starting point: string literal types and unions
Template literal types build on two older features: string literal types and unions of them. If you are fuzzy on either, the later chapters will feel like magic. This chapter reviews both, with attention to the behaviors that cause most real-world confusion: widening, inference from objects and arrays, and how unions flow through other type operators.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript types (
string,number,boolean) and how to write a type alias withtype. - The syntax of union types, such as
string | number. - Generic type parameters and constraints, such as
<T extends string>. - The shape of a mapped type,
{ [K in keyof T]: ... }. You do not need to be fluent with it yet.
You do not need any knowledge of template literal types. That is the next chapter.
What a string literal type is
The type string describes every possible string. A string literal type describes exactly one string value. You write it by putting the value in quotes where a type is expected.
type Up = "up";
const a: Up = "up"; // OK
// const b: Up = "down"; // Error: Type '"down"' is not assignable to type '"up"'The type "up" has exactly one member: the value "up". Comparison is exact and case-sensitive, so "Up" is a different type. The empty string "" is also a valid literal type.
Every string literal type is a subtype of string. A value of type "up" can go anywhere a string is expected. The reverse is not true, because a general string might hold any text.
const literal: "up" = "up";
const wide: string = literal; // OK: a literal is a string
let general: string = "anything";
// const narrow: "up" = general; // Error: Type 'string' is not assignable to type '"up"'Read the arrows as "is a wider type than". Moving down the diagram gives you fewer allowed values and more precision.
Unions of literals
One literal is rarely useful. A union of literals is. It lists the exact set of strings a value may take.
type Direction = "up" | "down" | "left" | "right";
function move(d: Direction): string {
return `moving ${d}`;
}
move("up"); // OK
// move("diagonal"); // Error: Argument of type '"diagonal"' is not assignable to parameter of type 'Direction'This gives you three practical benefits over a plain string parameter:
- The compiler rejects typos and unsupported values at the call site.
- Editors offer the allowed values as completions.
- Renaming or removing a member produces errors at every place that depended on it.
A union of literals is the closest thing TypeScript has to "a set of allowed strings". Template literal types take this set idea and let you compute new sets from existing ones.
Unions versus enums
Many codebases use a string enum for the same purpose. The two differ in important ways.
| Aspect | Union of literals | String `enum` |
|---|---|---|
| Runtime output | None. Types are erased. | An object is emitted. |
| Assigning a raw string | `"up"` works directly | A raw `"up"` is rejected; you must write `Direction.Up` |
| Works with template literal types | Yes, directly | No. Enum members are not plain string literal types. |
| Iterating the members | Needs a separate array | Possible through the emitted object |
The third row is the reason this tutorial uses unions. Template literal types operate on string literal types, and a union of them is the natural input.
Widening: why `const` and `let` differ
TypeScript infers a type for each declaration. For a string literal, the result depends on whether the value can change later.
const a = "up"; // type: "up"
let b = "up"; // type: stringA const can never be reassigned, so TypeScript keeps the precise literal type "up". A let can be reassigned, so TypeScript widens the type to string to allow later values. This widening is a common source of errors.
type Direction = "up" | "down" | "left" | "right";
declare function move(d: Direction): void;
let heading = "up";
// move(heading); // Error: Argument of type 'string' is not assignable to parameter of type 'Direction'The fix is to say what you mean. Annotate the variable, or use a const.
type Direction = "up" | "down" | "left" | "right";
declare function move(d: Direction): void;
let heading: Direction = "up";
move(heading); // OK
const fixed = "down";
move(fixed); // OK: const keeps the literal typeWidening inside objects
Widening is stricter for object properties. Properties are mutable by default, so even in a const object the property type widens.
type Direction = "up" | "down" | "left" | "right";
declare function move(d: Direction): void;
const config = { direction: "up" };
// config.direction has type string
// move(config.direction); // ErrorYou have two common ways to preserve the literal.
type Direction = "up" | "down" | "left" | "right";
declare function move(d: Direction): void;
// 1. A const assertion makes everything readonly and literal.
const config1 = { direction: "up" } as const;
move(config1.direction); // OK: type is "up"
// 2. An annotation states the intended type.
const config2: { direction: Direction } = { direction: "up" };
move(config2.direction); // OKThe as const assertion is the one you will use most often with template literal types, because it keeps values narrow enough to compute with.
Getting a union from a value
Sometimes you want one source of truth: an array of values at runtime, and a union type derived from it. Combine as const with typeof and an indexed access.
const directions = ["up", "down", "left", "right"] as const;
type Direction = (typeof directions)[number];
// "up" | "down" | "left" | "right"
function isDirection(value: string): value is Direction {
return (directions as readonly string[]).includes(value);
}
console.log(isDirection("up")); // true
console.log(isDirection("flip")); // falseWithout as const, the array would be typed string[] and Direction would collapse to string. With it, the array becomes a readonly tuple of literals. The [number] index then means "the type of any element", which is the union of all of them.
The cast to readonly string[] in isDirection is needed because includes on a tuple of literals only accepts those literals. A parameter of type string would be rejected without it.
Unions come from other places too
You do not always write a union by hand. Several type operators produce one.
type User = { id: number; name: string; active: boolean };
type UserKey = keyof User;
// "id" | "name" | "active"
type UserValue = User[UserKey];
// number | string | booleankeyof T returns the union of an object type's property names as string literals. This matters later: the mapped types with as clauses in Chapter 8 iterate over exactly this union.
Note that keyof can also include number or symbol keys. That is why you will often see keyof T & string in later chapters, which keeps only the string keys.
Operating on unions: narrowing, Extract, and Exclude
Narrowing and exhaustiveness
Because a union is a closed set, the compiler can verify that you handled every member. Assigning the leftover value to never turns a forgotten case into a compile error.
type Direction = "up" | "down" | "left" | "right";
function arrow(d: Direction): string {
switch (d) {
case "up":
return "↑";
case "down":
return "↓";
case "left":
return "←";
case "right":
return "→";
default: {
const unreachable: never = d;
return unreachable;
}
}
}
console.log(arrow("left")); // ←If you later add "forward" to Direction, the default branch fails to compile, because d is no longer never there. The error points you at every switch that needs updating.
Filtering with Extract and Exclude
Two built-in utility types select members of a union.
type Direction = "up" | "down" | "left" | "right";
type Vertical = Extract<Direction, "up" | "down">;
// "up" | "down"
type Horizontal = Exclude<Direction, Vertical>;
// "left" | "right"Extract<T, U> keeps the members of T that are assignable to U. Exclude<T, U> removes them.
Conditional types distribute over unions
When a conditional type is applied to a naked type parameter, it runs once for each union member and combines the results. This is called distribution.
type IsUp<T> = T extends "up" ? true : false;
type A = IsUp<"up">; // true
type B = IsUp<"up" | "down">; // boolean (true | false)Extract and Exclude work through this mechanism. Template literal types behave similarly: an operation applied to a union yields a union of per-member results. You will see this in Chapters 3 and 4.
Common mistakes
- Expecting
letto keep a literal.let x = "up"has typestring. Annotate it or useconst. - Forgetting
as conston arrays and objects. The inferred type becomesstring[]or{ key: string }, and any union derived from it collapses tostring. - Mixing up case.
"Up"and"up"are different types. Case is only changed by the intrinsic types in Chapter 4. - Assuming a function parameter infers a literal.
function f(x) {}withx: stringaccepts anything. Only an explicit literal union restricts it. - Using a string
enumand expecting it to compose with template literal types. Prefer a union of literals for that work. - Treating
stringas "any literal". Astringvalue is not assignable to a literal type, even if its content happens to match at runtime.
Looking ahead
You now have the raw material. A template literal type takes string literal types, or unions of them, and splices them together with the same ${} syntax you use in ordinary template strings. For example, ` Hello, ${string} describes every string that begins with Hello, `. The next chapter introduces that syntax. The union behavior reviewed here explains why combining unions inside a template produces every possible combination.
Exercise
Given const sizes = ["sm", "md", "lg"]; (no as const), what is the type of (typeof sizes)[number], and what change to the declaration makes it "sm" | "md" | "lg"?
Show answer
Without as const, TypeScript infers string[], so (typeof sizes)[number] is string. Writing const sizes = ["sm", "md", "lg"] as const; makes the array a readonly tuple of literals, so (typeof sizes)[number] becomes "sm" | "md" | "lg".
Exercise
Why does this code fail to compile, and give two ways to fix it? type Direction = "up" | "down"; declare function move(d: Direction): void; let heading = "up"; move(heading);
Show answer
let widens the inferred type of heading to string, and string is not assignable to Direction. Fix it by annotating the variable (let heading: Direction = "up";) or by declaring it with const (const heading = "up";), which keeps the literal type "up". Writing let heading = "up" as const; also works.
Exercise
Using only Direction = "up" | "down" | "left" | "right" and a built-in utility type, write the type "left" | "right". Then say what IsUp<"up" | "down"> evaluates to when type IsUp<T> = T extends "up" ? true : false.
Show answer
Exclude<Direction, "up" | "down"> gives "left" | "right". IsUp<"up" | "down"> evaluates to boolean, because the conditional type distributes over the union and produces true | false.