`` `prefix-${T}` `` — Build Strings at the Type Level
Template Literal Types
Template literal types let you compose strings at the type level — concat, transform case, build patterns.
What you'll learn
- Read template-literal type syntax
- Use built-in string manipulators
- Build constraint patterns
Template literal types are template strings at the type level. They distribute over unions and combine with mapped types for powerful string-pattern types.
The Basics
type Greeting = `Hello, ${string}!`;
const a: Greeting = "Hello, Ada!"; // ✓
const b: Greeting = "Goodbye!"; // ✗ ${string} is a placeholder for any string.
Distribute Over Unions
type Side = "top" | "bottom" | "left" | "right";
type Position = `margin-${Side}`;
// "margin-top" | "margin-bottom" | "margin-left" | "margin-right" The template distributes — each member of the union becomes a template with that value substituted.
Built-in String Manipulators
| Helper | Effect |
|---|---|
Uppercase<T> | "hi" → "HI" |
Lowercase<T> | "HI" → "hi" |
Capitalize<T> | "hello" → "Hello" |
Uncapitalize<T> | "Hello" → "hello" |
type Shouted = Uppercase<"hello">; // "HELLO"
type Methods = `get${Capitalize<"name" | "age">}`;
// "getName" | "getAge" Build Getters / Setters With Mapped Types
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type User = { name: string; age: number };
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number } string & K narrows K to a string (since object keys can also
be number / symbol). The mapped + template combo is how
libraries generate accessors.
Multiple Substitutions
type CssVar<NS extends string, K extends string> = `--${NS}-${K}`;
type ColorVar = CssVar<"color", "primary" | "danger">;
// "--color-primary" | "--color-danger" Patterns for Parsing
type ExtractRoute<S> = S extends `/${infer Path}` ? Path : never;
type R = ExtractRoute<"/about/contact">; // "about/contact" infer (next lesson but one) lets you extract a type out of a
template pattern.
Up Next
The big one — conditional types.
Conditional Types →