Sub topic 10
Rewriting Types to Be Cheaper to Check
This chapter assumes you can already read a --generateTrace result and a @typescript/analyze-trace report, which earlier chapters covered. You should also be comfortable with interfaces, generics, conditional types, and tsconfig.json. Here you will turn a hot spot that the trace found into a cheaper type, without changing what the program means.
Why the shape of a type changes the cost
The checker does most of its work when it compares one type to another, for example when you pass an argument, return a value, or assign to a variable. Some type shapes make that comparison cheap and some make it expensive. Three properties matter:
- Identity. A named type, such as an interface or a type alias, can be cached. The checker can see "this is the same
Useras before" and skip the work. - Flatness. An interface has a fixed list of members that is computed once. An intersection of several types must be resolved again each time it is used.
- Depth. A type that expands through many levels of generics or recursion creates many intermediate types. Each one costs time and memory.
The fixes in this chapter all push types toward more identity, more flatness, and less depth.
Change only what the trace points at
Rewriting every intersection in a codebase is a bad plan. Most types are cheap, and rewrites carry a risk of changing behavior. Take the type or file the analysis flagged and change that one thing. Then run npx tsc --noEmit --extendedDiagnostics again and compare the "Check time" line with your baseline. If the number did not move, the change did not help, and you should revert it.
Prefer interfaces that extend over large intersections
An intersection such as A & B & C is not turned into a single object type when you declare it. The checker keeps the pieces and, when the type is used, it has to check each piece and then work out the combined result. Each time that happens the work repeats. An interface that extends the same types has one flat member list, computed once and cached by name.
This is the slow form:
interface User {
id: string;
name: string;
}
interface Permissions {
roles: string[];
}
interface AuditInfo {
createdAt: Date;
}
// Slower to check: the intersection is recomputed and compared structurally at each use
type AdminUserIntersection = User & Permissions & AuditInfo;This is the usually cheaper form:
interface User {
id: string;
name: string;
}
interface Permissions {
roles: string[];
}
interface AuditInfo {
createdAt: Date;
}
// Usually cheaper: an interface has a name and cached members
interface AdminUser extends User, Permissions, AuditInfo {}
const admin: AdminUser = {
id: "1",
name: "Ada",
roles: ["admin"],
createdAt: new Date(),
};Check these limits before you convert:
interface ... extendsworks only with object types. You cannot extend a union type or a conditional type that has not been resolved.- If two parents declare the same property with incompatible types, an interface reports an error at the declaration. An intersection would silently produce
neverfor that property. The error is useful, but it means a conversion can surface bugs that were hidden. - A single intersection of two small types is not a problem. The gain shows up with long intersections, intersections with generics, and intersections used in many signatures.
Name types you repeat
An anonymous type written inline is built fresh where it appears. If it is a large mapped type, a long union, or the result of utility types such as Omit and Pick, every place that writes it out pays for it. A named alias gives the checker one type to reuse.
interface Payloads {
click: { x: number; y: number };
key: { code: string };
}
type EventName = keyof Payloads;
// Repeated inline: the same mapped type is written out in each signature
function addHandlers(h: { [K in EventName]?: (p: Payloads[K]) => void }): void {
console.log(Object.keys(h));
}
function removeHandlers(h: { [K in EventName]?: (p: Payloads[K]) => void }): void {
console.log(Object.keys(h));
}
// Named once and reused
type Handlers = { [K in EventName]?: (p: Payloads[K]) => void };
function addNamedHandlers(h: Handlers): void {
console.log(Object.keys(h));
}
function removeNamedHandlers(h: Handlers): void {
console.log(Object.keys(h));
}For a type this small the saving is negligible. Naming pays off when the type is large and appears dozens of times. It also keeps error messages and declaration files readable, because the compiler can print Handlers instead of the whole expanded shape.
Annotate the return types of exported functions
When you leave out a return type, the compiler infers it from the function body. Inference can be expensive when the body calls generic functions. For exported functions it costs twice, because declaration emit (declaration: true) must also write that inferred type out as text. If the type is large, the .d.ts output grows and every file that imports the function has to load it.
An explicit annotation stops inference at the boundary:
interface Config {
name: string;
size: number;
}
interface Store {
name: string;
items: Map<string, unknown>;
}
function buildStore(config: Config): Store {
return { name: config.name, items: new Map() };
}
// Inferred return type must be computed and printed for declaration emit
export function createStoreInferred(config: Config) {
return buildStore(config);
}
// Explicit annotation avoids re-inferring a large type
export function createStore(config: Config): Store {
return buildStore(config);
}Here Store is small, so you will not see a difference. The benefit appears when buildStore returns a deeply generic type, such as the result of a schema library or a chain of Omit, Pick, and mapped types. In that case the annotation also makes the public API explicit, so a change in the body cannot silently change what callers see.
The same applies to exported variables whose initializer is a complex expression. Annotate the variable's type if the trace shows time spent inferring it.
Keep unions manageable
Assigning a value to a union type means the checker may compare it against each member. Large unions of object types make this slow, and comparing two large unions can grow roughly with the product of their sizes. Some practical steps:
- Add a discriminant property, such as
kind: "circle", so the checker can pick the right member by one property check and skip the rest. - Avoid building unions from template literal types that multiply out, for example combining three unions of ten strings each into a thousand-member union.
- If a union is only used as a set of allowed strings,
keyofof a small interface or aconstobject is usually cheaper than a hand-written long union.
Tame deep conditional types
A recursive conditional type creates a new instantiation at each level. The compiler stops at a limit and reports error TS2589, "Type instantiation is excessively deep and possibly infinite". The limit is about 100 levels for ordinary recursion. Before TypeScript 4.5 that was the only form. Since 4.5, a conditional type whose recursive call is in tail position is evaluated in a loop, and the limit rises to about 1000.
A call is in tail position when the recursive reference is the entire branch result, with nothing wrapped around it. You usually get there by adding an accumulator parameter.
This version wraps the recursive call in a tuple, so it is not a tail call:
type ReverseSlow<T extends unknown[]> = T extends [infer Head, ...infer Rest]
? [...ReverseSlow<Rest>, Head]
: [];This version carries the result in Acc, and the recursive call is the whole branch:
type Reverse<T extends unknown[], Acc extends unknown[] = []> = T extends [
infer Head,
...infer Rest,
]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type Result = Reverse<[1, 2, 3]>;
const check: Result = [3, 2, 1];Beyond tail recursion, these habits keep conditional types cheap:
- Put the cheapest, most selective check first so most inputs exit early.
- Do not distribute over a large union unless you need to. Wrapping the checked type in a tuple, as in
[T] extends [U], turns off distribution. - Avoid recursion over large inputs, such as the keys of a type with hundreds of properties. If the recursion exists only to compute a lookup table, write the table out as an interface.
Summary of patterns
| Pattern in code | What the trace tends to show | Fix | Watch out for |
|---|---|---|---|
| `A & B & C` used widely | Many `checkTypeRelatedTo` events on the intersection | `interface X extends A, B, C` | Conflicting properties become errors; cannot extend unions |
| Exported function, no return type | Time in the inferring file; huge `.d.ts` | Explicit return annotation | You must keep the annotation in sync |
| Same large inline type repeated | Many instantiations of one shape | Name it with an alias or interface | Little gain for small types |
| Large unions of objects | Slow relation checks between unions | Discriminant property; smaller unions | Needs a common literal property |
| Deep recursive conditional type | TS2589 or very long instantiation | Tail-recursive form with accumulator | Not every recursion can be made tail recursive |
Common mistakes
- Rewriting without a baseline. If you did not record the check time before the change, you cannot tell whether the change helped.
- Replacing a type alias with an interface for no reason. The gain is for object types that were intersections. A plain
type Point = { x: number; y: number }is just as cheap. - Annotating with a type that is looser than the real one. If you write
: objector: anyto remove inference cost, you lose type safety for every caller. Annotate with the real, named type. - Chasing a small hot spot. The analysis lists the worst offenders first. Fixing a 30 ms item when a 4 s item is above it wastes effort.
- Leaving the fix undocumented. A later contributor may turn the interface back into an intersection because it looks tidier. A short comment that names the reason prevents this.
Exercise
A trace shows that an exported function loadConfig has no return type annotation, and the checker spends most of its time inferring the type that its body returns. The function returns buildConfig(raw), and buildConfig returns Omit<Base, "secret"> & Extras & Defaults. Name two changes that could reduce the cost, and say what you would do to confirm they worked.
Show answer
First, add an explicit return type to loadConfig, using a named type, so callers and declaration emit no longer re-infer it. Second, replace the intersection with a named interface, for example interface LoadedConfig extends Omit<Base, "secret">, Extras, Defaults {}, and use it as the return type. To confirm, run npx tsc --noEmit --extendedDiagnostics before and after, and compare the "Check time" line. You can also regenerate the trace and check that the hot spot for loadConfig has dropped in the analysis. If the number did not move, revert the change.
Exercise
Why does type Reverse<T, Acc> with an accumulator allow deeper inputs than a version that returns [...Reverse<Rest>, Head]?
Show answer
In the accumulator version, the recursive call is the whole result of the branch, which is a tail position. Since TypeScript 4.5 the compiler evaluates such conditional types in a loop and allows about 1000 levels. In the other version the recursive call is wrapped inside a tuple, so each level has to wait for the level below. That version stops at about 100 levels with error TS2589.