Sub topic 13
Limits and pitfalls
This chapter covers the places where built-in utility types behave differently from what their names suggest. It assumes you can read mapped types and conditional types at a basic level, and that you know Partial, Pick, Omit, Record, Exclude and ReturnType from the earlier chapters. Each pitfall below has a short example, the reason it happens, and a fix.
Shallow transformations
Partial, Required and Readonly change only the top-level properties. Nested objects keep their original shape.
interface Settings {
theme: { color: string; size: number };
}
type Shallow = Partial<Settings>;
const bad: Shallow = { theme: { color: "red" } }; // Error: property 'size' is missingThe mapped type { [K in keyof T]?: T[K] } applies ? to theme and leaves T["theme"] untouched. A recursive version fixes this:
interface Settings {
theme: { color: string; size: number };
tags: string[];
onChange: () => void;
}
type DeepPartial<T> = T extends (...args: never[]) => unknown
? T
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
const ok: DeepPartial<Settings> = {
theme: { color: "red" },
tags: ["a", undefined],
};Two details matter here. The first branch stops the recursion at functions, because mapping over a function type would discard its call signature. Mapped types over arrays also produce arrays, so tags becomes (string | undefined)[], which is why undefined is accepted inside the array above. If you do not want that, add a branch for arrays.
Readonly has the same shallow limit, and it only exists at compile time:
const cfg: Readonly<{ tags: string[] }> = { tags: ["a"] };
cfg.tags.push("b"); // allowed: the array itself is not readonly
// cfg.tags = []; // Error: Cannot assign to 'tags' because it is a read-only propertyAt runtime nothing is frozen. Use Object.freeze if you need enforcement, and readonly string[] or ReadonlyArray<string> for the array.
Omit does not distribute over unions
Omit<T, K> is defined as Pick<T, Exclude<keyof T, K>>. For a union T, keyof T contains only the keys that every member shares. The unique keys are lost before Pick runs.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type Collapsed = Omit<Shape, "kind">; // {}
type DistributiveOmit<T, K extends keyof any> = T extends unknown
? Omit<T, K>
: never;
type PerMember = DistributiveOmit<Shape, "kind">; // { radius: number } | { side: number }T extends unknown is the standard trick. A conditional type whose checked type is a bare type parameter distributes over a union, so Omit runs once per member. Pick has the same weakness, so use the same wrapper if you need it on a union.
Omit accepts keys that do not exist
The second parameter of Omit is K extends keyof any, which means any string | number | symbol. A typo is not an error:
interface User {
id: number;
name: string;
email: string;
}
type Oops = Omit<User, "emial">; // no error: same shape as User
type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
// type Checked = StrictOmit<User, "emial">; // Error: not assignable to keyof UserThe built-in is lenient on purpose. It lets you write generic code that omits a key that may or may not exist. For ordinary application types, a StrictOmit helper catches renames and typos at compile time.
Structural typing lets omitted properties through
A type built with Omit or Pick does not forbid the removed properties. It only stops requiring them. TypeScript checks extra properties only on fresh object literals.
interface User {
id: number;
name: string;
}
type NewUser = Omit<User, "id">;
function create(u: NewUser): void {
console.log(u);
}
const existing: User = { id: 1, name: "Ada" };
create(existing); // allowed: a User has everything a NewUser needs
// create({ id: 1, name: "Ada" }); // Error: object literal may only specify known propertiesIf create spreads u into a database insert, the id is still there at runtime. Strip fields explicitly when it matters, for example by destructuring const { id, ...rest } = u.
Partial allows undefined, and spread hides it
By default an optional property accepts an explicit undefined. Combined with object spread, this produces updates that silently erase data:
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Ada" };
const patch: Partial<User> = { name: undefined };
const merged = { ...user, ...patch };
console.log(merged.name); // undefined at runtime, yet typed as stringThe compiler treats a spread of an optional property as if a missing key leaves the earlier value in place. It does not account for an explicit undefined. Turning on exactOptionalPropertyTypes in tsconfig.json makes { name: undefined } an error for name?: string. Without it, filter out undefined values before merging.
Record and missing keys
Record<Role, T> with a literal union enforces exhaustive keys. Record<string, T> does the opposite, because it is an index signature that claims every string key exists.
const counts: Record<string, number> = {};
const n = counts["missing"]; // typed number, actually undefined at runtime
console.log(n.toFixed(2)); // compiles, throws TypeError when runYou have three options:
- Enable
noUncheckedIndexedAccess, so index reads becomenumber | undefined. - Type the map as
Partial<Record<string, number>>. - Use a
Map<string, number>when keys are truly dynamic.
An exhaustive Record<Role, string[]> has a related cost. Adding a role to the union breaks every such table, which is usually the point, but you should expect it.
Union filters and function types
Exclude, Extract and NonNullable all distribute over unions, so they work member by member. They also test assignability, not equality. Extract<string | number, string> is string, but Extract<"a" | "b", string> keeps both literals because each is assignable to string.
ReturnType and Parameters have their own limits:
declare function parse(x: string): number;
declare function parse(x: number): string;
type R = ReturnType<typeof parse>; // string: only the last overload is seen
type P = Parameters<typeof parse>; // [x: number]They also need a function type, not a function value. Writing ReturnType<parse> is an error, and ReturnType<typeof parse> is correct. For generic functions, type parameters are replaced by their constraints, so ReturnType<typeof identity> for <T>(x: T) => T gives unknown.
Awaited unwraps nested promises recursively, which matches what await does. It does not unwrap a function that returns a promise, so you still need Awaited<ReturnType<typeof fn>>.
Readability of derived types
Deeply composed types such as Partial<Omit<Pick<User, ...>, ...>> show up in editor hovers and error messages in expanded form, and the chain is hard to follow. If you use a composition more than once, give it a name. A small helper can also flatten what the editor shows:
type Prettify<T> = { [K in keyof T]: T[K] } & {};
interface User {
id: number;
name: string;
email: string;
}
type UpdatePayload = Prettify<Partial<Omit<User, "id">>>;Prettify changes nothing about what is assignable. It only forces the editor to display a plain object type.
Choosing under constraints
| Symptom | Cause | Fix |
|---|---|---|
| Nested property still required | `Partial` is shallow | `DeepPartial` |
| `Omit` on a union gives `{}` | `keyof` of a union keeps shared keys only | `DistributiveOmit` |
| Misspelled key in `Omit` compiles | `K extends keyof any` | `StrictOmit` |
| Omitted field still present at runtime | Structural typing | Destructure it out |
| `undefined` overwrites data | Optional allows `undefined` | `exactOptionalPropertyTypes` or filter |
| `Record<string, T>` read is unsafe | Index signature | `noUncheckedIndexedAccess` or `Map` |
| `ReturnType` of overloaded function | Last overload wins | Write the type by hand |
Exercise
Given type Event = { type: "click"; x: number } | { type: "key"; code: string }, what is Omit<Event, "type">, and how do you get { x: number } | { code: string } instead?
Show answer
Omit<Event, "type"> is {}, because keyof Event is only "type", the one key both members share, and removing it leaves nothing. Use a distributive wrapper: type DistributiveOmit<T, K extends keyof any> = T extends unknown ? Omit<T, K> : never; and then DistributiveOmit<Event, "type">, which runs Omit on each member separately.
Exercise
const merged = { ...user, ...patch } where patch: Partial<User> is typed as keeping name: string, yet merged.name can be undefined at runtime. Why, and which compiler option narrows the gap?
Show answer
An optional property accepts an explicit undefined value, and the compiler types a spread of an optional property as if a missing key keeps the earlier value. So { name: undefined } in patch overwrites name without a type error. Enabling exactOptionalPropertyTypes makes { name: undefined } an error for name?: string, so the case can no longer occur in typed code.
Exercise
Why is Readonly<{ tags: string[] }> not enough to stop cfg.tags.push("x"), and what two changes would stop it?
Show answer
Readonly only marks the top-level property tags as non-reassignable. The array it points to is still mutable. Type the property as readonly string[] (or ReadonlyArray<string>) to block push at compile time, and use Object.freeze if you also need runtime protection.