4 min read
•Question 19 of 48hardWhat are Template Literal Types?
String manipulation at the type level.
What You'll Learn
- Template literal type syntax
- String type manipulation
- Pattern matching
Template Literal Types
code.tsTypeScript
type Greeting = `Hello, ${string}`;
const g1: Greeting = "Hello, World"; // OK
const g2: Greeting = "Hi, World"; // ErrorWith Union Types
code.tsTypeScript
type Color = "red" | "blue" | "green";
type Size = "small" | "large";
type ProductId = `${Color}-${Size}`;
// "red-small" | "red-large" | "blue-small" | "blue-large" | ...Built-in String Utilities
code.tsTypeScript
type Upper = Uppercase<"hello">; // "HELLO"
type Lower = Lowercase<"HELLO">; // "hello"
type Cap = Capitalize<"hello">; // "Hello"
type Uncap = Uncapitalize<"Hello">; // "hello"Event Handler Pattern
code.tsTypeScript
type EventName = "click" | "focus" | "blur";
type Handler = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onBlur"
interface Handlers {
onClick: () => void;
onFocus: () => void;
onBlur: () => void;
}