← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 9 of 20

Template Literal Types

Template literal types build new string literal types by combining existing string literal types. They are useful for describing structured strings.

Basic Template Literal Type

A template literal type uses backticks and placeholders, just like a JavaScript template string, to combine existing string literal types into new, more specific string literal types.

Example: Basic Template Literal Type

typescript
type Greeting = `Hello, ${string}!`;
const g: Greeting = "Hello, Ravi!";
console.log(g);

Combining Unions

Template literal types can combine multiple unions to produce every valid combination of their members, which is useful for generating an exhaustive set of related string values from smaller pieces.

Example: Combining Unions

typescript
type Direction = "top" | "bottom";
type Side = "left" | "right";
type Combo = `${Direction}-${Side}`;
const c: Combo = "bottom-right";
console.log(c);

Event Names

Template literal types can create predictable, structured event names from property names — for example turning a property click into an event type onClick automatically.

Example: Event Names

typescript
type Prop = "click" | "hover";
type EventName = `on${Capitalize<Prop>}`;
const e: EventName = "onClick";
console.log(e);

Intrinsic String Utilities

Template literal types work together with built-in string utility types such as Uppercase, Lowercase, and Capitalize to transform the casing of the string literal types they produce.

Example: Intrinsic String Utilities

typescript
type Loud = Uppercase<"hello">;
type Quiet = Lowercase<"WORLD">;
const loud: Loud = "HELLO";
const quiet: Quiet = "world";
console.log(loud, quiet);

Practical Template Literal Types

Template literal types are useful for APIs, event systems, CSS-like values, and any other place where string values follow a predictable, structured pattern that's worth enforcing at the type level.

Example: Practical Template Literal Types

typescript
type HttpMethod = "GET" | "POST";
type Endpoint = "users" | "orders";
type Route = `${HttpMethod} /${Endpoint}`;
const r: Route = "POST /users";
console.log(r);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.