Sub topic 2
TypeScript Template Literal Types: Building and Parsing String Types
Assume you know basic TypeScript types, unions, generics, and mapped types. Template literal types use ${} to describe patterns in string types.
Changing Case with Built-In Helpers
TypeScript provides four intrinsic string types:
Uppercase<S>converts every character to uppercase.Lowercase<S>converts every character to lowercase.Capitalize<S>converts the first character to uppercase.Uncapitalize<S>converts the first character to lowercase.
They distribute over unions:
type Input = "click" | "focus";
type Upper = Uppercase<Input>; // "CLICK" | "FOCUS"
type Labels = `on${Capitalize<Input>}`; // "onClick" | "onFocus"
type Lower = Lowercase<"READY">; // "ready"
type Field = Uncapitalize<"Name">; // "name"Matching Families of Strings
A placeholder inside a template literal type describes a family of strings. A string placeholder accepts any string in that position. A number placeholder accepts numeric text.
type Greeting = `Hello, ${string}`;
type PixelValue = `${number}px`;
const message: Greeting = "Hello, Ada";
const width: PixelValue = "12.5px";Literal unions create every possible combination:
type Color = "red" | "blue";
type Size = "sm" | "lg";
type ClassName = `${Color}-${Size}`;
// "red-sm" | "red-lg" | "blue-sm" | "blue-lg"Conditional Types and `infer`
A conditional type chooses one type when a condition matches and another type otherwise:
type IsString<T> = T extends string ? true : false;infer declares a type variable inside a matching pattern. TypeScript infers that variable from the type being checked.
Extracting Parts with `infer`
Template patterns can capture text around a delimiter:
type RouteParam<S extends string> =
S extends `${string}:${infer Name}/${string}`
? Name
: S extends `${string}:${infer Name}`
? Name
: never;
type UserId = RouteParam<"/users/:id">; // "id"For multiple parameters, recurse over the remaining route:
type Params<S extends string> =
S extends `${string}:${infer Name}/${infer Rest}`
? Name | Params<`/${Rest}`>
: S extends `${string}:${infer Name}`
? Name
: never;
type Names = Params<"/users/:id/posts/:postId">;
// "id" | "postId"Exercise
What is the type of EventName<"click" | "blur"> when EventName<T extends string> = \on${Capitalize<T>}\``?
Show answer
"onClick" | "onBlur".