Mapped and conditional types
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Types that compute other types
So far we wrote types by hand or used the built-in utilities. In this lesson, we look at how those utilities are built. Once you understand mapped and conditional types, you can write your own, and the library type definitions you read stop looking like magic.
keyof and typeof
Two operators for looking at types:
const user = { id: 1, name: "Sara", active: true };
type User = typeof user; // { id: number; name: string; active: boolean }
type UserKey = keyof User; // "id" | "name" | "active"
const key: UserKey = "name";
console.log(key, user[key]);
typeof (in a type position) takes the type of a value. keyof produces a union of the property names of a type. We saw both in the generics lesson.
Mapped types
A mapped type loops over the keys of a type and builds a new object type. The syntax is { [K in keyof T]: ... }, which you can read as "for each key K in T".
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
interface Point {
x: number;
y: number;
}
const p1: MyPartial<Point> = { x: 1 };
const p2: MyReadonly<Point> = { x: 1, y: 2 };
// p2.x = 5; // Error: read-only
console.log(p1, p2);
This is how Partial and Readonly are defined. For each key K, the property keeps its type T[K], and we add ? or readonly.
Changing the modifiers
You can remove modifiers with a minus sign:
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
type Concrete<T> = {
[K in keyof T]-?: T[K];
};
interface Config {
readonly host: string;
port?: number;
}
const c: Mutable<Config> = { host: "localhost" };
c.host = "example.com";
const full: Concrete<Config> = { host: "a", port: 80 };
console.log(c.host, full.port);
-readonly removes readonly, and -? makes optional properties required. That is how Required<T> works.
Changing the value type
The right side does not have to be T[K]:
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type Stringified<T> = {
[K in keyof T]: string;
};
interface Product {
id: number;
price: number;
}
const draft: Nullable<Product> = { id: null, price: 100 };
const formValues: Stringified<Product> = { id: "1", price: "100" };
console.log(draft, formValues);
Stringified is handy for the type of a form, where every input value is text, even if the model has numbers.
Renaming keys with as
Since TypeScript 4.1 you can transform the key names with as, together with template literal types:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
const getters: PersonGetters = {
getName: () => "Sara",
getAge: () => 28,
};
console.log(getters.getName(), getters.getAge());
Capitalize is a built-in string type that upper-cases the first letter. The string & K is needed because keys can also be numbers or symbols, and Capitalize only accepts strings. You can also filter keys: if the as clause produces never for a key, that key is dropped.
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type Mixed = { id: number; name: string; city: string };
const s: OnlyStrings<Mixed> = { name: "Ali", city: "Lahore" }; // id is gone
console.log(s);
Conditional types
A conditional type chooses between two types, like a ternary operator for types: T extends U ? X : Y. If T is assignable to U, the result is X, otherwise Y.
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
const a: A = true;
const b: B = false;
console.log(a, b);
On its own, that looks like a toy. The strength comes from combining it with generics:
type ApiResult<T> = T extends string ? { text: T } : { value: T };
type R1 = ApiResult<string>; // { text: string }
type R2 = ApiResult<number>; // { value: number }
const r1: R1 = { text: "hi" };
const r2: R2 = { value: 5 };
console.log(r1, r2);
Distribution over unions
When the checked type is a bare type parameter and you give it a union, the condition is applied to each member separately, and the results are joined. This is called distribution.
type ToArray<T> = T extends unknown ? T[] : never;
type X = ToArray<string | number>; // string[] | number[]
const x: X = ["a"];
console.log(x);
This is how Exclude and Extract work:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type Letters = "a" | "b" | "c";
const ex: MyExclude<Letters, "a"> = "b";
const ext: MyExtract<Letters, "a" | "c"> = "c";
console.log(ex, ext);
For each member, MyExclude returns never if it matches, and never disappears from a union. What remains is the members that did not match.
infer: pulling a type out
Inside a conditional type, infer X declares a new type variable that TypeScript fills in for you from the matched shape.
type ElementType<T> = T extends (infer E)[] ? E : T;
type E1 = ElementType<string[]>; // string
type E2 = ElementType<number>; // number (not an array, so unchanged)
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
function makeUser() {
return { id: 1, name: "Ali" };
}
type U = MyReturnType<typeof makeUser>; // { id: number; name: string }
const e1: E1 = "a";
const e2: E2 = 5;
const u: U = makeUser();
console.log(e1, e2, u);
Read T extends (infer E)[] ? E : T as: "if T is an array of something, call that something E and give it back, otherwise give back T". ReturnType is built this way, with infer R capturing the return type.
Here is one more practical example, unwrapping promises:
type Unwrap<T> = T extends Promise<infer V> ? Unwrap<V> : T;
type P1 = Unwrap<Promise<number>>; // number
type P2 = Unwrap<Promise<Promise<string>>>; // string (recursive)
const p1: P1 = 1;
const p2: P2 = "x";
console.log(p1, p2);
The built-in Awaited<T> does this and handles more edge cases, so use that in real code.
Recursive mapped types
A mapped type can refer to itself to go through nested objects. DeepReadonly is the classic example:
type DeepReadonly<T> = T extends (infer E)[]
? ReadonlyArray<DeepReadonly<E>>
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
interface Settings {
theme: { name: string; colours: string[] };
}
const s: DeepReadonly<Settings> = { theme: { name: "dark", colours: ["black"] } };
// s.theme.name = "light"; // Error
// s.theme.colours.push("white"); // Error
console.log(s.theme.name);
A word of caution
These tools are powerful, and easy to overuse. Complex type-level code is hard to read, slow to compile and produces hard to read error messages. My guideline: write advanced types in shared library code, where they make the daily use simpler, and keep application code on plain interfaces and the built-in utilities. If you spend an afternoon on a clever type that saves ten lines, it was not a good trade.
Common mistakes
- **Forgetting that
T extends U ? ...distributes over unions.** Wrap in a tuple,[T] extends [U], to turn it off. - **Using
keyof Twith numeric or symbol keys and then expecting a string.** Usestring & K. - Building huge recursive types. The compiler has a depth limit and slows down.
- Testing types only by looking at them. Assign a value of the expected type to check the result.
- Reinventing a built-in. Check the utility type list first.
Try it yourself
- Write
Optionalize<T, K extends keyof T>that makes only the keysKoptional. Hint: useOmitandPartial<Pick<...>>. - Write
PickByType<T, V>that keeps only the properties whose value type extendsV. - Write
FirstArg<F>that extracts the first parameter type of a function usinginfer. - Create
Events<T>that turns{ click: MouseEvent }into{ onClick: (e: MouseEvent) => void }.
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
interface Point {
x: number;
y: number;
}
const p1: MyPartial<Point> = { x: 1 };
const p2: MyReadonly<Point> = { x: 1, y: 2 };
// p2.x = 5; // Error: read-only
console.log(p1, p2);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account