One source of truth
A User type appears in a sign-up form (without an id, which the server assigns), in a profile editor (every field optional), in a list (just id and name), and in the database layer (everything, read-only). Writing four separate interfaces works for a week. Then someone adds phone to one of them and not the others, and the types quietly disagree with each other and with reality.
TypeScript's answer is to compute types from types. Write User once, and derive the rest: Omit<User, "id">, Partial<User>, Pick<User, "id" | "name">, Readonly<User>. Change User, and everything derived from it changes too. The machinery behind these utilities, mapped types and conditional types, is available to you as well, and it turns the type system into a small programming language of its own: functions from types to types. This lesson covers the built-in utilities first, then the machinery, then the judgement about how far to take it.
The built-in utility types
// Utility types: new types computed from existing ones, so they never drift apart.
interface User {
id: string;
name: string;
email: string;
city?: string;
joined: Date;
}
type UserPatch = Partial<Omit<User, "id" | "joined">>; // every editable field, all optional
type UserPreview = Pick<User, "id" | "name">; // just what a list needs
type NewUser = Omit<User, "id" | "joined">; // what a sign-up form collects
const users = new Map<string, Readonly<User>>();
function createUser(input: NewUser): Readonly<User> {
const user: User = { ...input, id: `u-${users.size + 1}`, joined: new Date(Date.UTC(2026, 10, 19)) };
users.set(user.id, user);
return user;
}
function updateUser(id: string, patch: UserPatch): Readonly<User> {
const current = users.get(id);
if (current === undefined) throw new Error(`no user ${id}`);
const updated = { ...current, ...patch };
users.set(id, updated);
return updated;
}
const preview = (u: User): UserPreview => ({ id: u.id, name: u.name });
const ana = createUser({ name: "Ana Folau", email: "ana@example.org" });
const moved = updateUser(ana.id, { city: "Nuku'alofa" });
console.log(moved.city, moved.name, moved.joined.toISOString().slice(0, 10));
console.log(preview(moved));
// Types computed from functions and values.
async function loadSettings() {
return { theme: "dark" as "dark" | "light", fontSize: 16 };
}
type Settings = Awaited<ReturnType<typeof loadSettings>>; // { theme: "dark" | "light"; fontSize: number }
type CreateArgs = Parameters<typeof createUser>; // [input: NewUser]
const s: Settings = { theme: "light", fontSize: 14 };
const args: CreateArgs = [{ name: "Bo", email: "bo@example.org" }];
console.log(s.theme, args[0].name, users.size);
// Union utilities.
type Status = "draft" | "review" | "published" | "archived";
type Visible = Exclude<Status, "draft" | "archived">; // "review" | "published"
const visible: Visible[] = ["review", "published"];
console.log(visible.join(", "));
export {};Nuku'alofa Ana Folau 2026-11-19
{ id: 'u-1', name: 'Ana Folau' }
light Bo 1
review, publishedThe utilities you will use every week:
| Utility | Produces | Typical use |
|---|---|---|
Partial<T> | every property optional | patches, updates, defaults to merge |
Required<T> | every property required | the result of filling in defaults |
Readonly<T> | every property readonly | data that must not be mutated |
Pick<T, K> | only the properties K | a view of part of an object |
Omit<T, K> | all but the properties K | input without server-assigned fields |
Record<K, V> | an object with keys K, values V | lookup tables, dictionaries |
Exclude<U, X>, Extract<U, X> | union members not assignable / assignable to X | filtering literal unions |
NonNullable<T> | T without null and undefined | after a check |
ReturnType<F>, Parameters<F> | a function type's result / parameter tuple | wrapping functions you don't own |
Awaited<T> | what await would produce | results of async functions |
InstanceType<C>, ConstructorParameters<C> | from a class's constructor type | factories |
The program uses them as a real code base would. UserPatch is "any editable field, all optional", so updateUser(ana.id, { id: "u-99" }) is rejected ('id' does not exist in type 'Partial<Omit<User, "id" | "joined">>'), and the Readonly<User> returned from the store means moved.name = "Ana F." fails with Cannot assign to 'name' because it is a read-only property. Settings is computed from what loadSettings returns: typeof loadSettings turns the value into its function type, ReturnType extracts Promise<...>, and Awaited unwraps the promise. If someone adds a field to the settings, Settings gains it automatically.
A word on the two meanings of typeof. In an expression, typeof x is JavaScript's run-time operator and produces a string such as "object". In a type position, typeof x is TypeScript's type query and produces the static type of the variable x. The compiler always knows which one you mean from where it appears, and the type query is the bridge from the world of values to the world of types: typeof someConstant, keyof typeof someObject, ReturnType<typeof someFunction>. Most derived types in real code begin with it.
Mapped types and template literal types
Definition— mapped type
A mapped type, { [K in Keys]: Type }, builds an object type with one property for each member K of a union of keys, where Type may refer to K. Iterating over keyof T transforms each property of T. Modifiers add or remove readonly and ? (+readonly, -readonly, +?, -?), and an as clause renames keys or, by mapping them to never, removes them.
Partial<T> itself is defined in TypeScript's standard library as { [P in keyof T]?: T[P] }: a mapped type adding ?. Here are some of your own:
// Mapped types: build an object type by transforming each property of another.
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; // remove readonly
type Nullable<T> = { [K in keyof T]: T[K] | null }; // allow null everywhere
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K]; // rename keys with `as`
};
interface Station {
readonly code: string;
name: string;
elevation: number;
}
// A function whose return type is computed by Getters<T>.
function makeGetters<T extends object>(obj: T): Getters<T> {
const result: Record<string, () => unknown> = {};
for (const key of Object.keys(obj) as (keyof T & string)[]) {
result[`get${key[0].toUpperCase()}${key.slice(1)}`] = () => obj[key];
}
return result as Getters<T>;
}
const lhasa: Station = { code: "LXA", name: "Lhasa", elevation: 3650 };
const g = makeGetters(lhasa); // { getCode: () => string; getName: ...; getElevation: () => number }
console.log(g.getName(), g.getElevation() + 10, Object.keys(g));
const draft: Mutable<Station> = { ...lhasa };
draft.code = "LHA"; // allowed: readonly was removed
const blank: Nullable<Station> = { code: "TBD", name: null, elevation: null };
console.log(draft.code, blank.name ?? "(unnamed)");
// Filtering keys: keep only the properties whose values are numbers.
type NumericKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];
function total<T>(rows: T[], key: NumericKeys<T>): number {
return rows.reduce((sum, row) => sum + (row[key] as number), 0);
}
const stations: Station[] = [lhasa, { code: "LPB", name: "La Paz", elevation: 3640 }];
console.log(total(stations, "elevation"));
export {};Lhasa 3660 [ 'getCode', 'getName', 'getElevation' ]
LHA (unnamed)
7290Mutable<T>removesreadonlywith-readonly;Nullable<T>changes every property's type. These are one-line transformations of every property at once.Getters<T>renames keys withasand a template literal type: for each string keyK, the new key is`get${Capitalize<K>}`, sonamebecomesgetName.Capitalize,Uncapitalize,UppercaseandLowercaseare built-in string transformations at the type level. The return type ofmakeGettersis thereby computed from its argument, and the editor offersgetCode,getNameandgetElevationong. Notice that the implementation needs an assertion (as Getters<T>): the type system cannot follow string manipulation done at run time. This is typical, and a good reason to keep such functions small and tested.NumericKeys<T>is a classic idiom. The mapped type replaces each property's type with its own key if the value is a number and withneverotherwise; indexing the result with[keyof T]collects the surviving keys into a union. ForStation, that is just"elevation", sototal(stations, "name")is rejected withArgument of type '"name"' is not assignable to parameter of type '"elevation"'. This is the technique the generics lesson promised for constraining a key to properties of a certain type.
Template literal types are useful on their own, too: type EventName = `on${Capitalize<"click" | "focus">}` is "onClick" | "onFocus", and `#${string}` (lesson two) describes any string starting with #.
Conditional types and infer
Definition— conditional type
A conditional type, T extends U ? X : Y, evaluates to X if T is assignable to U, and to Y otherwise. In the extends clause, infer Name introduces a type variable that TypeScript fills in by matching, which lets you extract part of a type. When T is a bare type parameter and receives a union, the conditional is applied to each member separately and the results are joined: it distributes.
// Conditional types choose a type by testing another; `infer` captures part of a type.
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type IsString<T> = T extends string ? "yes" : "no";
type A = ElementOf<string[]>; // string
type B = IsString<"hello" | 42>; // "yes" | "no": conditional types distribute over unions
const a: A = "an element";
const b: B[] = ["yes", "no"];
console.log(a, b);
// Template literal types + infer: extract route parameters from a path pattern.
type RouteParams<Path extends string> =
Path extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof RouteParams<`/${Rest}`>]: string }
: Path extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
function buildPath<const P extends string>(pattern: P, params: RouteParams<P>): string {
return pattern.replace(/:(\w+)/g, (_, name: string) =>
encodeURIComponent((params as Record<string, string>)[name]),
);
}
console.log(buildPath("/users/:userId/posts/:postId", { userId: "42", postId: "hello world" }));
console.log(buildPath("/cities/:name", { name: "São Paulo" }));
console.log(buildPath("/about", {}));
// A tiny type-level test kit: these lines compile only if the types are what we claim.
type Equal<X, Y> = [X] extends [Y] ? ([Y] extends [X] ? true : false) : false;
type Expect<T extends true> = T;
type Tests = [
Expect<Equal<ElementOf<number[]>, number>>,
Expect<Equal<RouteParams<"/a/:x/b/:y">, { x: string; y: string }>>,
Expect<Equal<Awaited<Promise<Promise<boolean>>>, boolean>>,
];
const passed: Tests["length"] = 3;
console.log(`${passed} type-level tests compiled`);
export {};an element [ 'yes', 'no' ]
/users/42/posts/hello%20world
/cities/S%C3%A3o%20Paulo
/about
3 type-level tests compiledElementOf<T>asks "isTan array of something?" and, if so,infer Ecaptures that something.ElementOf<string[]>isstring;ElementOf<string>isnever. The built-insReturnType,ParametersandAwaitedare written exactly this way.- Distribution.
IsString<"hello" | 42>is evaluated for"hello"and for42separately, giving"yes" | "no". It is usually what you want (it is howExcludeworks); when it isn't, wrap both sides in brackets,[T] extends [U], to compare the union as a whole, asEqualdoes. RouteParamscombines everything: template literal types withinferpull each:paramout of a path pattern, recursion handles any number of them, and a mapped type turns them into an object type.buildPaththen demands exactly the right parameters for each pattern:buildPath("/users/:userId", { id: "42" })fails with'id' does not exist in type '{ userId: string; }'. Web frameworks and routers use this technique to type route handlers from their URL patterns.- Testing types.
EqualandExpectform a minimal test kit: eachExpect<Equal<A, B>>compiles only ifAandBare the same type. Add a false claim, such asExpect<Equal<ElementOf<number[]>, string>>, and the build fails withType 'false' does not satisfy the constraint 'true'. Libraries with complex types keep suites of such tests, often with a more carefulEqual(this simple one cannot tellanyapart from other types) or a dedicated tool.
Conditional types and recursion make TypeScript's type system expressive enough to compute almost anything, which is both fascinating and a warning. Lumenary Math's lambda calculus shows how little a language needs in order to compute everything.
Worked example: types derived from one value
The most useful everyday application of this lesson is not a clever recursive type but the habit of deriving types from a single run-time value. Here a table of roles and their permissions is the only place either is written down:
// One `as const` value drives every type: roles, permissions and a checked lookup.
const PERMISSIONS = {
viewer: ["read"],
editor: ["read", "write"],
admin: ["read", "write", "delete", "invite"],
} as const satisfies Record<string, readonly string[]>;
type Role = keyof typeof PERMISSIONS; // "viewer" | "editor" | "admin"
type Permission = (typeof PERMISSIONS)[Role][number]; // "read" | "write" | "delete" | "invite"
type PermissionsOf<R extends Role> = (typeof PERMISSIONS)[R][number];
function can(role: Role, permission: Permission): boolean {
return (PERMISSIONS[role] as readonly Permission[]).includes(permission);
}
// Exclude and the derived types work together.
type AdminOnly = Exclude<Permission, PermissionsOf<"editor">>; // "delete" | "invite"
const adminOnly: AdminOnly[] = ["delete", "invite"];
const roles = Object.keys(PERMISSIONS) as Role[];
for (const role of roles) {
const allowed = adminOnly.filter((p) => can(role, p));
console.log(`${role.padEnd(7)} write=${can(role, "write")} admin-only=${allowed.join("+") || "none"}`);
}
export {};viewer write=false admin-only=none
editor write=true admin-only=none
admin write=true admin-only=delete+inviteas const keeps every string as a literal, and satisfies checks the overall shape without widening it (lesson two). From there, each type is one step: keyof typeof PERMISSIONS is the union of role names; indexing with [Role][number] collects every permission that appears in any role; PermissionsOf<R> does the same for one role; and Exclude subtracts the editor's permissions to find what only an admin can do. Nothing is written twice. Add a "moderator" role with a "hide" permission to the object, and Role, Permission, can and every caller update themselves, while a call with a role or permission that doesn't exist is rejected. With a two-role version of the table, for example:
main.ts(8,5): error TS2345: Argument of type '"owner"' is not assignable to parameter of type '"viewer" | "editor"'.
main.ts(9,15): error TS2345: Argument of type '"publish"' is not assignable to parameter of type '"read" | "write"'.The two assertions that remain (as readonly Permission[] and as Role[]) are the familiar places where run-time APIs, includes and Object.keys, are typed more loosely than our data; each is local and obviously correct. This pattern, a constant table as the source of truth with types computed from it, is how many teams type feature flags, translation keys, analytics events, API endpoints and design tokens.
How far to go
Type-level programming is seductive. Every experienced TypeScript developer has written a type so clever that, six months later, nobody (including its author) could change it. Some guidance from practice:
- Use the built-ins first.
Partial,Pick,Omit,ReturnTypeand friends cover most needs and are understood by every reader. - Derive types from values where possible. A
constobject or array withas constandsatisfies, plustypeofandkeyof, often replaces a page of hand-written types with one source of truth that is also usable at run time. - Put complex types at library boundaries, not in application code. A router, a form library or a query builder may justify a
RouteParams-style type, written once, tested with type-level tests, and used by hundreds of call sites that never see its insides. Application code should read like ordinary code. - Name the pieces. A conditional type split into small, named aliases (
ElementOf,NumericKeys) is far easier to follow than one nested expression. - Watch the compiler's speed. Deeply recursive types can slow down type checking and the editor noticeably; TypeScript limits recursion depth and reports
Type instantiation is excessively deep and possibly infinitewhen you hit the limit. The--extendedDiagnosticsflag shows where checking time goes. - Error messages are part of the design. A type that produces a 40-line error for a simple mistake is a bad type, however correct.
Common misconceptions
Misconception
"Partial<T> makes nested objects partial too." It is shallow: only the top-level properties become optional. A DeepPartial must be written recursively, and is a good exercise.
Misconception
"Omit<T, K> checks that K is a key of T." It doesn't: Omit<User, "idd"> silently omits nothing. Some teams define a stricter version with K extends keyof T.
Misconception
"keyof and Object.keys give the same thing." keyof T is the set of keys the type declares. Object.keys(obj) returns the keys the object actually has at run time, which may include extra ones (structural typing allows them), so TypeScript types its result as string[], not (keyof T)[]. That is why the lesson's examples assert as Role[] only where the object is a known constant.
Misconception
"Mapped and conditional types run when the program runs." They exist only in the checker. A function whose type says it returns Getters<T> must still construct those getters at run time, and the compiler usually cannot verify that it does.
Misconception
"Conditional types always treat a union as one type." A conditional on a bare type parameter distributes over the members of a union. Wrap both sides in square brackets when you want to test the union as a whole.
Exercises
Work out each type by hand, member by member, then check in the Playground by hovering.
1. Utility, mapped and conditional types
Warm-upComputationalWhat is Exclude<"a" | "b" | "c", "a">? Write it as TypeScript prints it.
2. Utility, mapped and conditional types
Warm-upComputationalWith the lesson's User (id, name, email, city?, joined), which properties does Omit<User, "id" | "joined"> have? List their names.
3. Utility, mapped and conditional types
CoreComputationalWith type ElementOf<T> = T extends readonly (infer E)[] ? E : never;, which of these statements are true? Choose all that apply.
4. Utility, mapped and conditional types
CoreComputationalWith type IsString<T> = T extends string ? "yes" : "no";, what is IsString<"x" | 1>? Write it as TypeScript prints it.
5. Utility, mapped and conditional types
CoreComputationalWith the lesson's Getters<T> (keys renamed to `get${Capitalize<K>}`), what are the keys of Getters<{ a: 1; bc: 2 }>?
6. Utility, mapped and conditional types
CoreComputationalWhat does the lesson's buildPath("/files/:name", { name: "a b.txt" }) return?
7. Utility, mapped and conditional types
StretchComputationalWith type Status = "draft" | "review" | "published" | "archived";, what is Extract<Status, `${string}d`>? Write it as TypeScript prints it.
Further reading and resources
- TypeScript Handbook: Creating types from types · MicrosoftThe chapter covering keyof, typeof, indexed access, conditional, mapped and template literal types.
- TypeScript Handbook: Utility types · Microsoft
- TypeScript Handbook: Mapped types · Microsoft
- TypeScript Handbook: Conditional types · Microsoft
- TypeScript Handbook: Template literal types · Microsoft