Template Literal Types
In this page:
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
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
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
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
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
type HttpMethod = "GET" | "POST";
type Endpoint = "users" | "orders";
type Route = `${HttpMethod} /${Endpoint}`;
const r: Route = "POST /users";
console.log(r);
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates