Skip to content
TypeScript

Template Literal Types

Construct types based on strings.

By EZ4Code Team
template-literaltype

Code

type Greeting = `hello ${string}`;
const g: Greeting = "hello world";

type EventName = "click" | "hover";
type Handler = `on${Capitalize<EventName>}`;
// "onClick" | "onHover"

type Prop = "name" | "age";
type Getter = `get${Capitalize<Prop>}`;
// "getName" | "getAge"

// Union type combination
type Side = "top" | "right" | "bottom" | "left";
type Margin = `margin-${Side}`;
// "margin-top" | "margin-right" | ...

// Parse
type Split<S extends string> = S extends `${infer Head}.${infer Tail}` ? [Head, ...Split<Tail>] : [S];

Explanation

Template literal types generate combinations of string types.

More TypeScript Snippets