Lesson 112 of 296
Mapped, conditional and template literal types; infer
What you will learn
- Mapped types: transforming every property
- Rebuilding Partial, Pick and Omit yourself
- Key remapping with
as - Conditional types
infer- Template literal types
On this page
Mapped types
A mapped type goes through every key of a type and creates a new property for each:
type Flags<T> = {
[K in keyof T]: boolean;
};
type Features = { darkMode: string; beta: number };
type FeatureFlags = Flags<Features>; { darkMode: boolean; beta: boolean }[K in keyof T] reads as "for each key K of T".
Rebuilding Partial, Readonly, Pick and Omit
A task from the study plan.
Partial: add ? to every property:
type MyPartial<T> = {
[K in keyof T]?: T[K];
};Required: remove ? with -?:
type MyRequired<T> = {
[K in keyof T]-?: T[K];
};Readonly:
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};Pick: only map over the chosen keys:
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};Omit: pick every key except the removed ones:
type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;keyof any means "any valid key type": string | number | symbol. This is exactly how the built-in Omit is defined.
Key remapping with as
You can rename or filter keys:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Person = { name: string; age: number };
type PersonGetters = Getters<Person>;
{ getName: () => string; getAge: () => number }Mapping a key to never removes it:
type RemoveIds<T> = {
[K in keyof T as K extends "id" ? never : K]: T[K];
};Conditional types
A conditional type chooses a type based on a condition. It looks like the ternary operator:
T extends U ? X : Y"If T fits U, the type is X, otherwise Y."
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">; "yes"
type B = IsString<42>; "no"Distribution over unions
When T is a union, a conditional type is applied to each member separately, and the results are joined. This is called distributive behaviour:
type NoNull<T> = T extends null | undefined ? never : T;
type C = NoNull<string | null | number>; string | numberThis is exactly how NonNullable and Exclude work:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;infer
Inside a conditional type, infer declares a new type variable that TypeScript fills in by pattern matching:
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type R1 = MyReturnType<() => number>; number
type R2 = MyReturnType<(s: string) => boolean>; booleanRead it as: "if F is a function, call its return type R, and give back R".
More examples:
type ElementType<T> = T extends (infer U)[] ? U : never;
type E = ElementType<string[]>; string
type MyAwaited<T> = T extends Promise<infer V> ? MyAwaited<V> : T;
type V = MyAwaited<Promise<Promise<number>>>; number
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => any ? A : never;Template literal types
Build string literal types with template syntax:
type Size = "sm" | "md" | "lg";
type Color = "red" | "blue";
type ButtonClass = `btn-${Size}-${Color}`;
"btn-sm-red" | "btn-sm-blue" | "btn-md-red" | ... (all 6 combinations)
type EventName = "click" | "focus";
type Handler = `on${Capitalize<EventName>}`; "onClick" | "onFocus"
type ApiRoute = `/api/${string}`;
const r: ApiRoute = "/api/users"; fine
const bad: ApiRoute = "/users"; ErrorBuilt-in helpers: Uppercase, Lowercase, Capitalize, Uncapitalize.
How much of this do you need?
- Everyone should understand mapped types,
keyof, and simple conditional types, and be able to rebuild Partial, Pick and Omit. inferand complex template literal types are mainly for library authors and senior roles. Being able to read them and explain ReturnType is usually enough.- In application code, prefer simple, readable types over clever ones.
Common mistakes
- Writing very complex types that no teammate can understand.
- Forgetting that conditional types distribute over unions.
- Writing
[K in T]instead of[K in keyof T].
How to say it in an interview
"Mapped types iterate over keys with K in keyof T to build new types; that is how Partial, Readonly and Pick are defined, and Omit is Pick of the keys excluding K. Key remapping with as can rename or filter keys. Conditional types choose between types with T extends U ? X : Y and distribute over unions, which is how Exclude and NonNullable work. infer extracts a type by pattern matching, as in ReturnType. Template literal types build string unions like onClick. In application code I keep types as simple as possible."
Key words
| Word | Meaning |
|---|---|
| Mapped type | A type built by looping over keys |
| Key remapping | Renaming or filtering keys with as |
| Conditional type | T extends U ? X : Y |
| Distributive | Applied to each member of a union separately |
| infer | Captures a type inside a conditional type |
| Template literal type | A string type built with template syntax |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.