Sub topic 9
Recognizing Expensive Types and Excessive Instantiation
Assume you are comfortable with TypeScript interfaces, generics, union types, tsconfig.json, and running tsc. This chapter focuses on the checker phase, where TypeScript compares types, expands generic types, and evaluates conditional types.
A type can be expensive even when the program is small. The cost usually comes from the shape of the type, how often it is used, and how deeply the compiler must expand it.
What makes a type expensive?
The checker works structurally. To decide whether two types are compatible, it compares their members. Complex types can cause repeated comparisons or create many intermediate types.
Common warning signs include:
- Large intersection types that combine many object types.
- Deeply nested conditional or mapped types.
- Generic types used with many different type arguments.
- Recursive types that expand repeatedly.
- Exported values whose types must be inferred and printed.
- Very wide unions, especially when combined with conditional types.
The following table connects a pattern with its typical cost.
| Pattern | Why it can be slow | First response |
|---|---|---|
| Large intersection | Members may be recomputed and compared repeatedly | Use a named interface when possible |
| Deep conditional type | Each union member may take a separate branch | Reduce nesting or split the type |
| Recursive generic | Instantiations can grow until the depth limit | Add a simpler boundary type |
| Unannotated export | The compiler must infer and serialize a large type | Add an explicit public type |
Understanding instantiation
An instantiation is a concrete version of a generic type. For example, Box<string> is an instantiation of Box<T>. A conditional type can create many instantiations when it distributes over a union.
type Box<T> = {
value: T;
};
type Unwrap<T> = T extends Box<infer Value> ? Value : never;
type Values = Unwrap<Box<string> | Box<number> | Box<boolean>>;Here, Unwrap is evaluated separately for each member of the union. That behavior is useful, but a large union combined with several nested conditional types can multiply the work.
Recursive utilities are another source of excessive instantiation:
type DeepReadonly<T> = {
readonly [Key in keyof T]: T[Key] extends object
? DeepReadonly<T[Key]>
: T[Key];
};
type Configuration = DeepReadonly<{
server: {
host: string;
limits: {
requests: number;
};
};
}>;This example is reasonable because the object is shallow. In a real codebase, applying several recursive utilities to a large schema can produce thousands of intermediate types. Very deep expansion may end with TS2589: Type instantiation is excessively deep and possibly infinite.
Use traces to find the actual hotspot
After generating a trace with --generateTrace, run @typescript/analyze-trace. Look for repeated operations involving the same generic, conditional type, or source file. The goal is to identify a type that consumes checking time, not merely the longest type declaration.
A useful investigation loop is:
- Record the baseline checker time.
- Find a repeated or unusually expensive type operation.
- Simplify one type pattern.
- Run the same measurement again.
- Keep the change only if the relevant time improves without damaging type safety.
The following diagram shows the relationship between a source type, its instantiations, and the checker.
Rewrite expensive type shapes
A named interface can give the checker a stable set of members to reuse. An intersection may still be appropriate, but compare both forms when a hot type appears in a trace.
interface User {
id: string;
}
interface Permissions {
canDelete: boolean;
}
interface AuditInfo {
createdAt: Date;
}
type AdminUserIntersection = User & Permissions & AuditInfo;
interface AdminUser extends User, Permissions, AuditInfo {}
function canRemoveUser(user: AdminUser): boolean {
return user.canDelete;
}
const administrator: AdminUser = {
id: "u-1",
canDelete: true,
createdAt: new Date()
};
console.log(canRemoveUser(administrator));Explicit annotations also create a boundary around public APIs. Without one, the compiler may infer and later serialize a large type.
interface Store {
get(key: string): string | undefined;
}
interface Config {
initial: Record<string, string>;
}
function buildStore(config: Config): Store {
return {
get(key) {
return config.initial[key];
}
};
}
export function createStore(config: Config): Store {
return buildStore(config);
}Prefer simpler public types over exposing a chain of conditional helpers. Keep advanced utilities inside implementation files when callers only need a small, named result.
Exercise
A trace shows that a deeply nested conditional type is instantiated for a union of 40 members. What should you try first?
Show answer
Confirm the hotspot with a baseline, then reduce the conditional type's nesting or replace it at the public boundary with a simpler named type. Measure again after the change.