TypeScript · Lesson 30 of 42
Template literal types
Build string types from other types with template literal syntax, use Uppercase and Capitalize, and generate keys like onClick or getName from a union.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to describe strings by their pattern, not only by an exact list. This is a TypeScript feature with no counterpart in plain JavaScript, and it is behind many of the nicest library types, such as typed event names and CSS-like value strings.
The basics
A template literal type uses the same backtick syntax as template strings, but in a type position:
type UserId = `user-${number}`;
const a: UserId = "user-42";
console.log(a);user-42The type accepts strings that begin with user- and continue with something that is a valid number. Anything else is rejected:
type UserId = `user-${number}`;
const bad: UserId = "admin-42";example.ts(3,7): error TS2322: Type '"admin-42"' is not assignable to type '`user-${number}`'.The placeholders can hold string, number, boolean, bigint, or a union of literals:
type Greeting = `Hello, ${string}!`;
const g: Greeting = "Hello, Asha!";
console.log(g);Hello, Asha!Unions multiply out
When a placeholder holds a union, the template produces one string per combination:
type Colour = "red" | "blue";
type Size = "small" | "large";
type Variant = `${Colour}-${Size}`;
const options: Variant[] = ["red-small", "red-large", "blue-small", "blue-large"];
console.log(options.length);4Variant has exactly four members. Adding a colour automatically adds more variants to the type, which is much better than writing every string by hand.
Intrinsic string types
TypeScript provides four built-in types that transform a string literal type:
type Upper = Uppercase<"hello">;
type Lower = Lowercase<"HELLO">;
type Cap = Capitalize<"name">;
type Uncap = Uncapitalize<"Name">;
const values: [Upper, Lower, Cap, Uncap] = ["HELLO", "hello", "Name", "name"];
console.log(values);[ 'HELLO', 'hello', 'Name', 'name' ]These are most useful inside templates, to build names that follow a convention.
Typed event handler names
A realistic case: for a list of events, generate the matching handler property names, such as onClick:
type EventName = "click" | "focus" | "blur";
type HandlerName = `on${Capitalize<EventName>}`;
type Handlers = Record<HandlerName, () => void>;
const handlers: Handlers = {
onClick: () => console.log("clicked"),
onFocus: () => console.log("focused"),
onBlur: () => console.log("blurred"),
};
handlers.onFocus();focusedHandlerName is "onClick" | "onFocus" | "onBlur". Add "submit" to EventName, and the compiler immediately demands an onSubmit handler.
With mapped types: generating getters
Combine a template literal type with key remapping from the mapped types lesson to build new property names from old ones:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type User = { name: string; age: number };
const getters: Getters<User> = {
getName: () => "Asha",
getAge: () => 30,
};
console.log(getters.getName(), getters.getAge());Asha 30For every key K of User, a property named get plus the capitalised key is created, whose value is a function returning the original property type. The & string limits the keys to strings, because numbers and symbols cannot be capitalised.
Pulling parts out with infer
Template literal types can also be matched against strings with infer, which pairs well with the conditional types lesson:
type FirstWord<S extends string> = S extends `${infer Head} ${string}` ? Head : S;
const a: FirstWord<"hello world"> = "hello";
const b: FirstWord<"single"> = "single";
console.log(a, b);hello singleIf the string contains a space, Head captures the part before it. This is the tool behind type-safe route parameters and query builders in some libraries, and it is a fine place to stop: you now know the tool exists, and you can read it when you meet it.
Common mistakes
Producing huge unions. Three unions of ten members each make a thousand strings. Large unions slow the compiler.
Using string where a pattern would do. If a value must look like user-123, a template type documents and enforces that.
Forgetting that types vanish. A template literal type checks literal values in your code. It cannot check a string that arrives at run time; check that with a type guard.
Capitalising non-string keys. Use keyof T & string when building names.
Exercise
Define Axis = "x" | "y" and Direction = "positive" | "negative" and a Movement type combining them as x-positive and so on. Define a CssLength type as `${number}px` | `${number}rem` and use it for a function parameter. Then write Setters<T> that generates setName-style methods from the properties of a type.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.