Skip to lesson

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.

Beginner to advanced·13 min·Advanced types·Updated 2026-11-24

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:

typescript
type UserId = `user-${number}`;

const a: UserId = "user-42";
console.log(a);
result
user-42

The type accepts strings that begin with user- and continue with something that is a valid number. Anything else is rejected:

typescript
type UserId = `user-${number}`;

const bad: UserId = "admin-42";
result
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:

typescript
type Greeting = `Hello, ${string}!`;

const g: Greeting = "Hello, Asha!";
console.log(g);
result
Hello, Asha!

Unions multiply out

When a placeholder holds a union, the template produces one string per combination:

typescript
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);
result
4

Variant 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:

typescript
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);
result
[ '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:

typescript
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();
result
focused

HandlerName 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:

typescript
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());
result
Asha 30

For 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:

typescript
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);
result
hello single

If 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.

Next: Classes: properties, methods and access modifiers.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What strings does the type `item-${number}` accept?
02 What does `${"a" | "b"}-${1 | 2}` produce?
03 What does Capitalize<"name"> give?
04 What is a typical use of template literal types with mapped types?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses