Sub topic 4
Homomorphic Mapped Types and How They Preserve Structure
This chapter assumes you can write a basic mapped type such as { [K in keyof T]: T[K] }, and that you know keyof, indexed access T[K], and the readonly, ?, - and + modifiers from earlier chapters. You should also be comfortable with generic type parameters and unions.
A mapped type can look the same in two different forms and still behave differently. In one form TypeScript copies the original property modifiers, treats arrays and tuples specially, and splits unions. In the other it does none of that. This chapter explains the difference, so you can predict which one you get and fix the cases where you get the wrong one.
What "homomorphic" means
A mapped type is homomorphic when its key set comes directly from keyof T, where T is a type parameter or a type that was written as one. The word means "same shape": the output has the same keys as the input, so TypeScript can copy more than the key names from T.
type Config = { readonly host: string; port?: number };
type Copy<T> = { [K in keyof T]: T[K] };
type A = Copy<Config>;
// { readonly host: string; port?: number }The mapped type never mentioned readonly or ?, yet both survive. TypeScript looks at T to find the modifiers and applies them to each output property. That is why Partial<T> only needs to write ? and Readonly<T> only needs to write readonly. Everything else about the properties is inherited.
Compare a version where the keys are written out by hand:
type Config = { readonly host: string; port?: number };
type Manual = { [K in "host" | "port"]: Config[K] };
// { host: string; port: number | undefined }The keys are the same, but Manual is not homomorphic. Nothing tells TypeScript to look at Config for modifiers, so readonly disappears and port becomes required. It still accepts undefined because Config["port"] is number | undefined.
The three behaviors you get
Homomorphism gives you three things, and each one matters when you write helpers.
- Modifiers (
readonlyand?) are preserved unless you add or remove them explicitly. - Arrays and tuples map element by element and stay arrays and tuples.
- Unions distribute, and primitives pass through unchanged.
The diagram shows the decision TypeScript makes.
Modifier preservation
Preservation is the default, and you override it with + or -. The built-in utilities depend on it. The Concrete helper from the earlier chapter removes optionality and keeps readonly, because the mapped type only mentions -?:
type Concrete<T> = { [K in keyof T]-?: T[K] };
type Config = { readonly host: string; port?: number };
type ConcreteConfig = Concrete<Config>;
// { readonly host: string; port: number }In a homomorphic mapped type, -? also strips undefined from the property type when the property was optional. That is why port is number here and not number | undefined.
The same preservation applies when you add an as clause that renames keys. The modifiers follow the original key:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Config = { readonly host: string; port?: number };
type ConfigGetters = Getters<Config>;
// { readonly getHost: () => string; getPort?: () => number | undefined }The getter for port is optional because port was optional. Check whether that is what you want. If every getter should exist, add -? after the closing bracket of the key part.
Arrays and tuples
When a homomorphic mapped type is instantiated with an array or tuple type, TypeScript maps over the elements and builds an array or tuple back. It does not map over the array's methods.
type Stringify<T> = { [K in keyof T]: string };
type S1 = Stringify<[number, boolean]>; // [string, string]
type S2 = Stringify<number[]>; // string[]
type S3 = Stringify<readonly number[]>; // readonly string[]This makes typed helpers over argument lists possible. The function below wraps every argument and keeps the position of each type:
type Boxed<T> = { [K in keyof T]: { value: T[K] } };
function box<T extends unknown[]>(...items: T): Boxed<T> {
return items.map((value) => ({ value })) as unknown as Boxed<T>;
}
const boxed = box(1, "a", true);
// type: [{ value: number }, { value: string }, { value: boolean }]
console.log(boxed[1].value.toUpperCase()); // ABecause T is inferred as the tuple [number, string, boolean], boxed[1] is known to hold a string. The as unknown as cast is needed because TypeScript cannot prove that the runtime array matches a generic mapped type.
Unions and primitives
When T is a union, a homomorphic mapped type is applied to each member and the results are joined. This is the same idea as distribution in conditional types, but it happens for a different reason, and you do not need extends to trigger it.
type Frozen<T> = { readonly [K in keyof T]: T[K] };
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type FrozenShape = Frozen<Shape>;
// | { readonly kind: "circle"; readonly radius: number }
// | { readonly kind: "square"; readonly side: number }Without distribution, keyof Shape would only be the keys common to both members, which is "kind". The result would lose radius and side.
Primitives map to themselves:
type Copy<T> = { [K in keyof T]: T[K] };
type P1 = Copy<string>; // string
type P2 = Copy<42>; // 42
type P3 = Copy<string | { a: 1 }>; // string | { a: 1 }This is why Partial<string> is just string and does not produce an object type with string methods.
How homomorphism is lost
TypeScript recognizes the pattern by the shape of the constraint after in. Small changes break it.
The built-in Pick is homomorphic even though it does not write keyof T directly. Its key type K is a type parameter that is constrained to keyof T, and TypeScript follows that constraint to find the source type:
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type Config = { readonly host: string; port?: number };
type HostOnly = MyPick<Config, "host">;
// { readonly host: string }Record is the opposite case. Its key type is constrained to keyof any, which says nothing about a source type, so it never copies modifiers:
type MyRecord<K extends keyof any, V> = { [P in K]: V };
type R = MyRecord<"host" | "port", string>;
// { host: string; port: string }The more common mistake is wrapping keyof T in another type. Intersecting with string is a typical way to get valid template literal keys, and it changes how TypeScript sees the constraint:
type Config = { readonly host: string; port?: number };
type Wrapped<T> = { [K in keyof T & string]: T[K] };
type W = Wrapped<Config>;
// { host: string; port: number | undefined }Here readonly and ? are gone, because the constraint is an intersection and not keyof T. The same happens with Extract<keyof T, string>. When you need string keys and want to keep modifiers, the pattern from earlier chapters keeps the plain keyof T constraint and converts inside the as clause or the template, as in Getters above with string & K.
Writing the type against a concrete union also avoids distribution:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type NotDistributed = { [K in keyof Shape]: Shape[K] };
// { kind: "circle" | "square" }Distribution only happens when the union arrives through a type parameter. If you want it, put the mapped type inside a generic alias and pass the union in.
Summary of forms
| Form | Modifiers copied | Arrays and tuples stay arrays | Distributes over unions | Column |
|---|---|---|---|---|
| `{ [K in keyof T]: ... }` | Yes | Yes | Yes | |
| `{ [K in keyof T as ...]: ... }` | Yes | No | Yes | |
| `{ [P in K]: ... }` with `K extends keyof T` | Yes | No | No | |
| `{ [K in keyof T & string]: ... }` | No | No | No | |
| `{ [P in "a" \ | "b"]: ... }` | No | No | No |
The table reflects the usual cases. When a result surprises you, hover over the type in your editor and compare it with the closest row.
Putting it to use
A realistic helper combines modifier control with preservation. This one makes the listed keys required and leaves the rest alone:
type RequireKeys<T, K extends keyof T> = T & { [P in K]-?: T[P] };
type Options = { host?: string; port?: number; debug?: boolean };
type WithHost = RequireKeys<Options, "host">;
const ok: WithHost = { host: "localhost" };
console.log(ok.host.length); // 9{ [P in K]-?: T[P] } is homomorphic through the constraint on K, so only host changes. Intersecting with T keeps the other optional properties. Writing it with a plain Record<K, T[K]> would drop the modifiers and lose the optional status of the properties you did not mention in other code paths.
Exercise
Given type Config = { readonly host: string; port?: number }, what is { [K in keyof Config & string]: Config[K] }, and how would you change it so that readonly and ? are preserved while keeping the same keys?
Show answer
The result is { host: string; port: number | undefined }. The intersection keyof Config & string is not a plain keyof T, so the modifiers are not copied. To keep them, write the constraint as keyof T in a generic alias, for example type Copy<T> = { [K in keyof T]: T[K] }. If you need a string-only key for a template literal, use string & K inside an as clause or the property type and leave the constraint alone.
Exercise
What does type Stringify<T> = { [K in keyof T]: string } produce for Stringify<[number, boolean]>, and what changes if you add as K to the mapped type?
Show answer
Without the as clause, the result is the tuple [string, string], because a homomorphic mapped type maps over the elements of a tuple. With as K, the array and tuple handling no longer applies, and TypeScript builds an object type from the tuple's keys, so the result is no longer a tuple.