Sub topic 9
Template literal types for string keys
This chapter shows how to build and take apart string types in TypeScript. You can then compute property names inside mapped and conditional types. It assumes you can read a basic mapped type ({ [K in keyof T]: T[K] }), a conditional type (T extends U ? X : Y), and infer, and that you know what a string literal type is.
What a template literal type is
A template literal type uses the same backtick syntax as a JavaScript template string, but in a type position. It describes a set of strings.
type Greeting = `hello ${string}`;
const ok: Greeting = "hello world";
const alsoOk: Greeting = "hello ";
// const bad: Greeting = "goodbye"; // Error: not assignable to `hello ${string}`Greeting is not a single string. It is every string that starts with hello . The ${string} part is a placeholder that accepts any string. When the placeholders are literal types, the result is a literal type:
type Name = "Ada";
type Hello = `hello ${Name}`; // "hello Ada"The placeholder can be string, number, bigint, boolean, null, undefined, or a literal or union of those. It cannot be symbol or an object type. That restriction matters when you use keyof, as shown below.
Unions multiply
When a placeholder is a union, TypeScript produces one string for every combination. The result is a cross product.
type Side = "top" | "bottom";
type Axis = "left" | "right";
type Corner = `${Side}-${Axis}`;
// "top-left" | "top-right" | "bottom-left" | "bottom-right"With several placeholders, the sizes multiply. Two unions of 10 members give 100 strings. Three unions of 50 members give 125,000 strings, which exceeds the compiler's limit of 100,000 union members and fails with an error about a union type that is too complex.
${boolean} expands to "true" | "false", because boolean is itself the union true | false.
If any placeholder is never, the whole template becomes never. This is the empty cross product, and it explains several surprising results later.
Intrinsic string types
TypeScript provides four built-in types that transform string literals. The compiler implements them directly, so you cannot write them in TypeScript yourself.
| Type | Effect | Example result |
|---|---|---|
| `Uppercase<S>` | All characters upper case | `Uppercase<"id">` is `"ID"` |
| `Lowercase<S>` | All characters lower case | `Lowercase<"ID">` is `"id"` |
| `Capitalize<S>` | First character upper case | `Capitalize<"name">` is `"Name"` |
| `Uncapitalize<S>` | First character lower case | `Uncapitalize<"Name">` is `"name"` |
They distribute over unions, so Capitalize<"a" | "b"> is "A" | "B". Combined with a template, they turn property names into related names:
type Prefixed<S extends string> = `on${Capitalize<S>}Change`;
type E = Prefixed<"email" | "age">; // "onEmailChange" | "onAgeChange"Why `keyof T` needs `& string`
keyof T is not always a string. For a generic T it can be string | number | symbol. Neither Capitalize nor a template placeholder accepts symbol, so this fails to compile:
// Error: Type 'keyof T' does not satisfy the constraint 'string'.
// type GetterName<T> = `get${Capitalize<keyof T>}`;Intersecting with string keeps only the string keys:
type GetterName<T> = `get${Capitalize<keyof T & string>}`;
type Names = GetterName<{ id: number; name: string }>;
// "getId" | "getName"Writing Extract<keyof T, string> gives the same result. The chapter's earlier Getters and ChangeHandlers examples use the same trick (string & K, keyof T & string).
Using templates as mapped type keys
A template can build the key set of a mapped type directly. The in clause accepts any union of string literals:
type Direction = "x" | "y";
type Position = { [K in `pos${Uppercase<Direction>}`]: number };
// { posX: number; posY: number }More often you derive new keys from the keys of an existing type, using the as clause covered in the next chapter. Here is a complete, runnable example:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
function makeGetters<T extends Record<string, unknown>>(obj: T): Getters<T> {
const result: Record<string, () => unknown> = {};
for (const key of Object.keys(obj)) {
const name = `get${key.charAt(0).toUpperCase()}${key.slice(1)}`;
result[name] = () => obj[key];
}
return result as unknown as Getters<T>;
}
const user = makeGetters({ id: 1, name: "Ada" });
console.log(user.getName()); // "Ada"
console.log(user.getId() + 1); // 2The type-level rename (Capitalize<K>) and the runtime rename (toUpperCase on the first character) must agree. TypeScript cannot check that the function body matches the declared return type, which is why the cast is needed. The type is a promise that you keep.
Matching patterns with `infer`
A conditional type can test a string against a template and capture the parts. The infer keyword works inside placeholders:
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"a.b.c", ".">; // ["a", "b", "c"]Head captures everything before the first occurrence of the separator. Tail captures the rest. The type recurses on Tail until no separator remains. The separator D must not be an empty string.
The matching rules are fixed:
- A placeholder followed by a literal text matches the shortest run of characters up to the first occurrence of that text.
- The last placeholder matches whatever is left.
- When two
inferplaceholders sit next to each other with no text between them, the first one captures exactly one character.
The last rule gives you a way to walk a string one character at a time:
type FirstChar<S extends string> = S extends `${infer F}${infer _}` ? F : never;
type F1 = FirstChar<"hello">; // "h"
type F2 = FirstChar<"">; // neverThe empty string does not match, so the false branch runs.
Converting snake_case to camelCase
Putting the pieces together, this helper converts a literal string and then renames every key of an object type:
type SnakeToCamel<S extends string> =
S extends `${infer Head}_${infer Tail}`
? `${Head}${Capitalize<SnakeToCamel<Tail>>}`
: S;
type CamelKeys<T> = {
[K in keyof T as K extends string ? SnakeToCamel<K> : K]: T[K];
};
type Row = { user_id: number; first_name: string };
type Model = CamelKeys<Row>;
// { userId: number; firstName: string }The conditional K extends string ? ... : K leaves symbol keys alone instead of failing on them.
Filtering by pattern
A template with ${string} is also a useful filter. Intersecting a union of keys with a pattern keeps only the keys that match it:
type HandlerKeys<T> = keyof T & `on${string}`;
type Props = { id: string; onClick: () => void; onHover: () => void };
type H = HandlerKeys<Props>; // "onClick" | "onHover""id" does not match on${string}, so its intersection is never and disappears from the union. This is shorter than a conditional type, and it also works as a constraint on a generic parameter.
Parsing numbers
Since TypeScript 4.8, infer can carry a constraint. This lets you turn a numeric string into a number literal type:
type ParseNum<S extends string> = S extends `${infer N extends number}` ? N : never;
type P1 = ParseNum<"8080">; // 8080
type P2 = ParseNum<"abc">; // never
type Port = `${number}`; // any string that is a valid number, such as "80" or "1e3"${number} is a pattern type, like ${string}. It does not enumerate numbers. It accepts any string that JavaScript would round-trip as a number.
Gotchas
| Situation | What happens |
|---|---|
| A placeholder is `never` | The whole template is `never` |
| A placeholder is `string` | The result is a pattern type, not a literal. It cannot be enumerated or used as a mapped type key set without becoming an index signature |
| A union of unions is large | Compile error once the result passes 100,000 members |
| Deep recursion over a long string | Recursion limits apply. Write the recursive call in tail position, and TypeScript can iterate far deeper |
| `keyof T` includes `symbol` | Error unless you intersect with `string` or test with `extends string` |
| Input is `string`, not a literal | `Split<string, ".">` falls through to `[string]` because no literal separator can be found |
The last two rows share a cause. These helpers work on literal types. If a value has been widened to string, for example by assigning it to a let variable, the helper can no longer see its contents. Use as const or const declarations to keep literal types.
Exercise
Write a type Prefix<T, P extends string> that renames every string key of an object type T by adding the prefix P and capitalizing the original key. For example, Prefix<{ id: number; name: string }, "user"> should be { userId: number; userName: string }. Which part of the mapped type makes symbol keys safe?
Show answer
type Prefix<T, P extends string> = { [K in keyof T & string as ${P}${Capitalize<K>}]: T[K] }; The keyof T & string in the in clause removes number and symbol keys before the template sees them, so Capitalize<K> always receives a string.
Exercise
What are the results of Split<"a--b", "-"> and ` ${"x" | "y"}${never} , given the Split` type from this chapter?
Show answer
Split<"a--b", "-"> is ["a", "", "b"]. The first match takes Head "a" and Tail "-b". The second match takes Head "" (the text before the next "-") and Tail "b", and "b" has no separator, so it ends the list. The second type is never, because a never placeholder makes the whole template never, even when the other placeholder is a union.