Sub topic 10
Rewriting Types to Be Cheaper to Check
Assume you can write TypeScript with interfaces, generics, and union types. You should also know how to run tsc and read a tsconfig.json. This chapter focuses on type shapes that make the checker repeat work.
TypeScript uses structural typing. It compares the members of types instead of comparing only their names. That flexibility can become expensive when a type contains many intersections, nested conditional types, or inferred object types.
Prefer named shapes over repeated intersections
An intersection combines several types with &:
type User = {
id: string;
name: string;
};
type Permissions = {
canDelete: boolean;
};
type AuditInfo = {
createdAt: Date;
};
type AdminUser = User & Permissions & AuditInfo;
function removeUser(user: AdminUser): void {
if (user.canDelete) {
console.log(`Removing ${user.id}`);
}
}The checker must repeatedly combine and compare the members of the intersection. This is often fine for small types, but large intersections used throughout a program can increase check time.
A named interface gives the checker one reusable shape:
interface AdminUser extends User, Permissions, AuditInfo {}This is usually cheaper when the members are object types with compatible properties. It also gives diagnostics a shorter, more useful name.
| Pattern | Typical effect | Main caution |
|---|---|---|
| Repeated large intersection | More structural work at each use | Convenient for composition |
| Named interface | Reusable cached member shape | Works only with compatible object members |
| Named type alias | Shorter references and diagnostics | Does not always prevent complex expansion |
The two forms are not identical in every situation. An interface cannot extend a union, and conflicting properties may produce different errors. Measure the change instead of applying it mechanically.
Add explicit boundaries to inference
Inference is useful inside a function, but exported values create larger costs. For an exported function, TypeScript may need to infer a complex return type and then print that type in declaration output.
interface Config {
prefix: string;
}
interface Store {
get(key: string): string | undefined;
}
function buildStore(config: Config): Store {
const values = new Map<string, string>();
return {
get(key) {
return values.get(`${config.prefix}:${key}`);
}
};
}
export function createStore(config: Config): Store {
return buildStore(config);
}The explicit Store return type creates a boundary. It documents the public API, limits the amount of inferred type information that escapes, and can reduce declaration-generation work.
Use annotations at public boundaries first:
- Exported functions and methods
- Public class properties
- Values passed between project-reference boundaries
- Large object literals whose inferred type appears in many locations
Do not annotate every local variable automatically. Local inference is usually cheap and often makes code clearer.
Reduce conditional-type expansion
Conditional types select one type based on another type:
type ElementType<T> = T extends readonly (infer U)[] ? U : T;
type Item = ElementType<readonly string[]>; // stringA conditional type distributes over a union when its checked type is a naked type parameter:
type ToArray<T> = T extends unknown ? T[] : never;
type Result = ToArray<string | number>; // string[] | number[]Many nested distributive conditionals can produce a large number of intermediate types. Recursion can also reach the compiler's instantiation-depth limit.
Ways to reduce this work include:
- Split one deeply nested conditional into named helper types.
- Constrain generic parameters so impossible cases disappear early.
- Avoid distributing over a union when distribution is not required.
- Prefer a finite mapped type or a runtime lookup when the relationship is simple.
- Stop recursive types at a documented depth.
To prevent distribution, wrap the checked type in a tuple:
type ToArrayWithoutDistribution<T> =
[T] extends [unknown] ? T[] : never;
type Result = ToArrayWithoutDistribution<string | number>;
// (string | number)[]Read the result in a trace
If a trace identifies a type alias or generic helper as a hot spot, simplify that type in isolation. Change one pattern at a time, then compare the checker time and total type count from --extendedDiagnostics.
flowchart TD
A[Find a hot type in the trace] --> B[Name the repeated shape]
B --> C[Add public annotations]
C --> D[Simplify intersections or conditionals]
D --> E[Run extended diagnostics]
E --> F{Did check time improve?}
F -->|Yes| G[Keep the change and add a regression check]
F -->|No| H[Revert or test another type boundary]caption: A measured loop for simplifying expensive TypeScript types alt: A flowchart from finding a trace hot spot through changing and measuring a type
Exercise
Why can an explicit return type make an exported function faster to check?
Show answer
It prevents the compiler from carrying a large inferred return type across the public boundary and reduces the work needed to print that type.