Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 96 ยท Type Manipulation

Template Literal Types

Learn template literal types - build string types from unions, use Uppercase and Capitalize, type event names and routes, and parse strings with infer.

You already know JavaScript's template literals: `Hello, ${name}!` builds a string from pieces. Template literal types do the same thing with types. `user:${number}` is the type of every string that starts with user: followed by a number, and `${'sm' | 'lg'}-button` is the union 'sm-button' | 'lg-button'.

That sounds like a small trick, but it unlocks a lot. You can derive method names like onClick from event names like 'click', check that a CSS-like value ends in px, type the parameters of a URL pattern such as '/users/:id', or convert camelCase keys to kebab-case, all at compile time with no runtime cost. Combined with the mapped types and conditional types from the previous two lessons, they're the last big building block of type-level TypeScript.

The examples again use the Expect/Equal helper from the utility types lesson: if a program prints its last line, every type check in it passed.

Building string types

A template literal type uses backticks and ${...} like the JavaScript feature, but inside the braces you put types:

TypeScript String types from pieces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

When a placeholder holds a union, the template is expanded for every member, and with several unions you get every combination (the cross product). ButtonClass has six members even though you wrote only five literals. That's convenient, but it also means unions can grow fast; you'll see the limit near the end of this lesson.

Pattern types: string, number and friends

A placeholder doesn't have to be a literal. Put a wide type such as string, number or bigint inside it and you get a pattern: an infinite set of strings with a fixed shape. TypeScript checks string literals against the pattern.

TypeScript Patterns like ${number}px (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This example fails on purpose, so nothing runs. The compiler reports two errors:

TEXT
main.ts(11,10): error TS2345: Argument of type '"320em"' is not assignable to parameter of type '`${number}px`'.
main.ts(14,7): error TS2322: Type '"red"' is not assignable to type '`#${string}`'.

${number} accepts any text that JavaScript would read as a number, so '12.5px' passes. Delete the two bad lines and the program prints both widths.

Keep in mind what a pattern does not do: #${string} only checks that the string starts with #; it can't check that six hex digits follow. And like every type, the pattern only checks values the compiler can see. A string read from user input is just string, and you still have to validate it at runtime, for example with a custom type guard that returns value is Pixels.

Pattern types also work as index signatures, such as { [key: data-${string}]: string }, which accepts any key that starts with data-. The index signatures lesson shows this in action.

Changing case: Uppercase, Lowercase, Capitalize, Uncapitalize

TypeScript has four built-in intrinsic string types. They're implemented inside the compiler rather than in a .d.ts file, and they transform string literal types:

Type Example Result
Uppercase<S> Uppercase<'get'> 'GET'
Lowercase<S> Lowercase<'POST'> 'post'
Capitalize<S> Capitalize<'click'> 'Click'
Uncapitalize<S> Uncapitalize<'UserId'> 'userId'

They work on unions too, member by member, and they're most useful inside templates:

TypeScript Case conversion in types and values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

toUpperCase() returns a plain string in the standard library types, so the functions assert the precise type with as. That's safe here because the runtime code and the type do the same transformation, but it's your job to keep them in sync. TypeScript won't check that text.toLowerCase() is wrong for a return type of Uppercase<S>.

Typed event names

A classic use is an object that emits '<property>Changed' events. Template literal types let the compiler derive the valid event names, and the callback's parameter type, from the object's own properties:

TypeScript A watched object with typed change events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at how the types flow in user.on('nameChanged', ...). TypeScript matches the string 'nameChanged' against the pattern `${K}Changed` and infers K = 'name'. Then the callback's parameter becomes T['name'], which is string, so newName.toUpperCase() compiles without an annotation. Write user.on('nameChange', ...) or call newAge.toUpperCase() and the program won't compile.

The implementation contains two small assertions, because the listener map stores callbacks for many different value types. That's typical: a precise public API with a few carefully placed casts inside. The event system project builds a complete emitter along these lines.

Template literals in key remapping

In the mapped types lesson you renamed keys with as. Template literal types are what make that useful. Here's a type that generates a setter for every property, and another that reverses it by matching the set prefix:

TypeScript
type Setters<T> = {
  [K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};

type Settings = { theme: string; fontSize: number };
// Setters<Settings> is
// { setTheme: (value: string) => void; setFontSize: (value: number) => void }

type PropertyFromSetter<S> = S extends `set${infer Name}` ? Uncapitalize<Name> : never;
// PropertyFromSetter<'setFontSize'> is 'fontSize'

The second type introduces the most powerful part of this feature: using infer inside a template to take strings apart.

Parsing strings with infer

A template literal type can appear on the right of extends as a pattern, with infer capturing the parts. TypeScript matches literal text in the pattern exactly, and each infer placeholder captures as little as possible (except the last one, which takes the rest). Combined with recursion, that's enough to write small parsers:

TypeScript Trim, Split and kebab-case at the type level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

How Split<'red,green,blue', ','> evaluates:

  1. The pattern `${infer Head},${infer Tail}` matches with Head = 'red' (the shortest prefix before a comma) and Tail = 'green,blue'.
  2. The type recurses on 'green,blue', giving 'green' and 'blue'.
  3. 'blue' has no comma, so the false branch returns ['blue'], and the tuples are spread together.

KebabCase walks one character at a time: ${infer First}${infer Rest} captures a single character in First. A character is uppercase if it equals Uppercase of itself; then the type emits a dash and the lowercase letter.

Typing route parameters

Web frameworks often define routes as strings like '/users/:userId/posts/:postId'. With a recursive template literal type you can turn that string into the exact object of parameters the route needs, so a missing or misspelled parameter is a compile error:

TypeScript Route parameters from a path pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

RouteParams finds the first :name/ segment, captures the name, and recurses on the rest of the path; the second branch handles a parameter at the very end. Each step builds a mapped type over the collected names, so RouteParams<'/users/:userId/posts/:postId'> is { userId: string; postId: string }. The @ts-expect-error line proves that a call with a missing parameter doesn't compile. (Without the directive, the error would be TS2741: "Property 'postId' is missing in type '{ userId: string; }' but required in type '{ postId: string; userId: string; }'.")

This only works when the route is a literal the compiler can see. If the path comes from a variable typed string, Path is just string, the patterns can't match, and RouteParams falls back to {}. Type-level parsing is a tool for strings written in your source code, not for data that arrives at runtime.

Limits to keep in mind

Template literal types are expressive, but they have real costs:

  • Union explosion. Every combination is a separate member. Ten digits in five placeholders is 10^5 = 100,000 members, and TypeScript refuses: error TS2590: Expression produces a union type that is too complex to represent. In practice, keep crossed unions small, and use a pattern like ${number} instead of enumerating values.
  • Recursion depth. Parsers that walk character by character (like KebabCase) recurse once per character. Long strings can hit the instantiation depth limit (error TS2589), as explained in conditional types.
  • Compile time and readability. Clever string types slow down the editor and are hard for teammates to debug. Use them where they protect a public API (event names, routes, CSS tokens), not everywhere.
  • No runtime effect. Types are erased. A function typed to return Uppercase<S> must still call toUpperCase().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many members does `${'a' | 'b'}-${'x' | 'y' | 'z'}` have?

    Placeholders with unions expand to every combination, so 2 times 3 gives 6 string literal types.
  2. 2. Does const w: ${number}px = '2.5px'; compile?

    The number placeholder matches strings that JavaScript would parse as a number, including decimals like 2.5.
  3. 3. What is Capitalize<'userId'>?

    Capitalize uppercases only the first character and leaves the rest unchanged.
  4. 4. For S extends `${infer H},${infer T}` ? H : never with S = 'a,b,c', what is the result?

    The first infer placeholder captures as little as possible before the literal comma, so H is 'a' and T is 'b,c'.
  5. 5. Why can't RouteParams check a path stored in a variable of type string?

    Type-level parsing needs a literal type the compiler can see. A plain string has no known content to take apart.

Summary

  • Template literal types build string types from pieces: `btn-${Size}`. Unions in placeholders expand to every combination.
  • Wide types in placeholders, such as ${number}px or user:${string}, create patterns that string literals are checked against.
  • Uppercase, Lowercase, Capitalize and Uncapitalize transform string literal types; they're built into the compiler.
  • With generics, a call like on('nameChanged', ...) can infer the property name from a string and type the callback accordingly.
  • infer inside a template pattern takes strings apart; with recursion you can write Trim, Split, case converters and route-parameter parsers.
  • Watch the limits: union size (TS2590), recursion depth (TS2589), compile speed, and the fact that types never validate runtime data.

Next: Advanced Type-Level Programming