Sub topic 3
Renaming and Parsing String Types with TypeScript
Assume you know type aliases, string literal unions, generics, and basic mapped types. This chapter uses those features to build names from strings and inspect string patterns.
Renaming object keys with `as` clauses
A mapped type can use as to create a new key for every property. A template literal type builds the new name:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type Person = {
name: string;
age: number;
};
type PersonGetters = Getters<Person>;
const getters: PersonGetters = {
getName: () => "Ada",
getAge: () => 36
};keyof T & string keeps only string keys. Capitalize<K> changes the first character. The value type still comes from the original property.
Practical patterns
The same technique describes event handler names:
type EventHandler<T extends string> = `on${Capitalize<T>}`;
type Handlers = EventHandler<"click" | "focus">;
// "onClick" | "onFocus"Template literals can also extract route parameters. Conditional types test a pattern, and infer captures a matching section:
type RouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type UserPostParams =
RouteParams<"/users/:id/posts/:postId">;
// "id" | "postId"Recursive types: splitting strings
A recursive conditional type can process one delimiter at a time:
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"a-b-c", "-">;
// ["a", "b", "c"]Each match returns the first part and calls Split on the remainder.
Limits and pitfalls
Large unions expand into every combination. Recursive types can exceed the compiler's instantiation-depth limit. Broad types such as string also reduce precision, because TypeScript cannot know their exact contents. Keep generated unions small, add recursion stopping conditions, and test inference with representative examples.
Exercise
What type does EventHandler<"save" | "cancel"> produce?
Show answer
"onSave" | "onCancel".