Sub topic 13
When Annotations Help: Intent, Recursive Types, and Performance
This chapter assumes you know generics, structural typing, and the three kinds of variance (covariant, contravariant, invariant). It also assumes you know the in, out, and in out modifiers from TypeScript 4.7 and later. You should compile with "strict": true. This chapter covers when writing the modifiers is worth the effort.
Annotations are optional
TypeScript works out the variance of every type parameter by itself. If you write interface Producer<T> { get(): T }, the compiler treats Producer<Dog> as assignable to Producer<Animal> without any annotation. Adding out does not change which programs compile in the usual case. It changes three other things:
- It records your intent in the declaration.
- It makes the compiler report a violation at the declaration instead of at a distant use site.
- It gives the compiler a shortcut for comparing instantiations.
Each of these is a reason to annotate. If none applies, leave the annotation off.
Use case 1: stating intent and catching drift
A generic type usually has a role. A read-only source should stay a source. Without an annotation, nothing stops a later edit from adding a write path. The type silently becomes invariant, and code far away that relied on covariance starts failing.
Here is a declaration that protects itself:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Source<out T> {
get: () => T;
}
const dogSource: Source<Dog> = { get: () => new Dog() };
const animalSource: Source<Animal> = dogSource; // OK: Source is covariant
console.log(animalSource.get().name);Suppose a teammate later adds a setter to Source:
// Compile with "strict": true (or "strictFunctionTypes": true)
interface Source<out T> {
get: () => T;
set: (value: T) => void; // Error: T is used in an input position, which contradicts out
}The error appears on the line that was edited. Without the out, the declaration would compile. The failures would show up later, wherever someone assigned a Source<Dog> to a Source<Animal>. Those errors are harder to trace back to the cause.
The annotation can only protect you where the compiler can see the violation. Method declarations are checked bivariantly, so a method such as set(value: T): void would not trigger the error above. If you want the annotation to catch drift, declare members as function-typed properties.
Annotating more strictly than the structure requires
You can write in out on a type that is currently only covariant. The compiler accepts it, because invariance only narrows what is assignable. This reserves room to add write operations later without breaking callers, since no caller could have relied on covariance. It is a design choice, and it costs some flexibility today.
interface Cache<in out T> {
read: (key: string) => T | undefined;
}Use case 2: recursive types
Variance measurement gets harder when a type refers to itself. To measure a parameter's variance, the compiler compares instantiations of the type using marker types and looks at the result. For a recursive type, that comparison can reach the same type again before it has finished. Complex members such as conditional types and mapped types add further trouble. In these cases the compiler may mark the measured variance as unreliable or unmeasurable. It then falls back to comparing the types structurally, member by member.
The fallback is correct, but it can be slow. For deeply nested recursive types it can also end in errors such as "Type instantiation is excessively deep and possibly infinite."
An explicit annotation removes the need to measure. The compiler trusts your declaration, after verifying it once. Here is a recursive tree:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Tree<out T> {
value: T;
children: ReadonlyArray<Tree<T>>;
}
const dogTree: Tree<Dog> = {
value: new Dog(),
children: [{ value: new Dog(), children: [] }],
};
const animalTree: Tree<Animal> = dogTree; // OK: compares Dog to Animal, no deep walk
console.log(animalTree.children[0].value.name);Once Tree is declared out, assigning Tree<Dog> to Tree<Animal> reduces to the question "is Dog assignable to Animal?" The compiler does not need to walk children, then the children of each child, and so on.
Note the use of ReadonlyArray<Tree<T>>. A mutable Tree<T>[] would make the covariance unsound, as the array chapter showed. The compiler would still accept out there, because arrays are checked covariantly. Annotating does not make an unsound type sound.
Use case 3: performance
Large codebases with heavy generics, such as state-management libraries, schema builders, and type-level parsers, can spend a lot of check time comparing instantiations. When the variance of a parameter is known, comparing Foo<A> with Foo<B> becomes a comparison of A with B. When it is not known, the compiler may expand both types and compare their members.
Do not annotate for speed on a hunch. Measure first:
- Run
tsc --extendedDiagnostics --noEmitand note "Check time" and "Instantiations". - Add annotations to the suspected hot types.
- Run it again and compare.
For a deeper look, tsc --generateTrace ./trace --noEmit writes a trace that you can open in a trace viewer such as Chrome's tracing tool. It lists which types took the longest to check. Annotations are worth keeping only if the numbers change. In most projects they will not.
Choosing between the options
| Situation | Annotate? | Why |
|---|---|---|
| Small internal type, used in one file | Usually no | Inference is correct and cheap. |
| Public library interface such as `Source<T>` or `Sink<T>` | Yes | Documents the contract and catches accidental changes. |
| Recursive type with many levels of nesting | Yes, then measure | Avoids fallback structural comparison. |
| Type already compiles quickly | No | No measurable benefit. |
| Type parameter used in mapped or conditional types | Test it | Inference may be marked unreliable, and the annotation may help. |
| Parameter that may later gain a write path | Consider `in out` | Prevents callers from depending on covariance. |
Pitfalls
- Wrong annotation, wrong error location. If an annotation contradicts the structure, the error is reported on the member that breaks it. Read the message to see which position (input or output) conflicts, then decide whether to fix the member or the annotation.
- Method bivariance hides violations. As shown above, a method that takes
Tdoes not tripout. A passing annotation does not prove the type is sound. - Annotations do not change runtime behavior. They exist only at compile time and vanish from the emitted JavaScript.
- A false sense of safety.
outonBox<out T>with a mutable array field compiles, but the unsoundness remains.
Summary of the reasons to annotate
- Intent. The declaration states how
Tmay be used, and edits that break it fail at the declaration. - Recursive and complex types. The compiler skips variance measurement that may be unreliable or slow.
- Performance. Instantiations are compared by their type arguments. Verify this with
--extendedDiagnostics.
Exercise
You maintain interface Emitter<T> { subscribe: (listener: (value: T) => void) => void } in a shared library. Which annotation fits, and why would adding set: (value: T) => void to it fail if you declared the parameter as out T?
Show answer
T appears only in the parameter of listener, and listener is itself a parameter. Two inversions cancel, so T is in an output position and Emitter<T> is covariant. out T is correct. Adding set: (value: T) => void puts T in an input position of a function-typed property. Under strictFunctionTypes that is checked contravariantly, so it contradicts out. The compiler reports an error on the set line. If set were declared as a method, set(value: T): void, the bivariant check would let it pass and the annotation would not catch the change.
Exercise
A type Node<T> is recursive and slows your build. Describe the steps to decide whether to add out T, and name the compiler flag you use to measure the effect.
Show answer
First run tsc --extendedDiagnostics --noEmit and record "Check time" and "Instantiations". Next confirm T is used only in output positions, using function-typed properties and ReadonlyArray rather than mutable arrays. Then add out T and fix any errors the compiler reports. Run the diagnostics again and compare. Keep the annotation if check time drops or if it documents intent you want to protect.