TypeScript
Beginner
1 min read
Template Literal Type Aliases
Example
// Basic template literal type
type Greeting = `Hello, ${string}!`;
const g: Greeting = "Hello, World!"; // OK
// Combining unions — cartesian product
type Color = "red" | "green" | "blue";
type Shade = "light" | "dark";
type Swatch = `${Shade}-${Color}`;
// "light-red" | "light-green" | "light-blue"
// | "dark-red" | "dark-green" | "dark-blue"
const s: Swatch = "dark-blue";
// Generate event handler names
type EventName = "click" | "focus" | "blur";
type Handler = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onBlur"
// Typed CSS property access
type CSSProperty = "margin" | "padding";
type CSSDirection = "Top" | "Right" | "Bottom" | "Left";
type CSSLonghand = `${CSSProperty}${CSSDirection}`;
// "marginTop" | "marginRight" | ... | "paddingLeft"
// Extract prefix from a string type
type RoutePrefix<T extends string> = T extends `/${infer Rest}` ? Rest : T;
type Route = "/users" | "/posts" | "home";
type Unprefixed = RoutePrefix<Route>; // "users" | "posts" | "home"
// Getter/setter pairs
type GetterSetter<T extends string> = {
[K in T as `get${Capitalize<K>}`]: () => string;
} & {
[K in T as `set${Capitalize<K>}`]: (v: string) => void;
};
type NamedField = GetterSetter<"name" | "email">;
// { getName: () => string; setName: (v) => void;
// getEmail: () => string; setEmail: (v) => void }
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript