Sub topic 8
How TypeScript measures variance on its own
This chapter assumes you know generic interfaces, structural typing, and the strict compiler option. It also assumes you have seen Producer<T> (covariant) and Consumer<T> (contravariant) from the earlier chapters.
You have not written a single in or out so far, yet Producer<Dog> was assignable to Producer<Animal>. The compiler worked out the variance by itself. This chapter explains how it does that and where the process can surprise you.
The setup
Every example in this chapter uses the same two classes.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}What "measuring" means
When you declare a generic type, TypeScript does not decide variance from the keywords you wrote. It decides by experiment, the first time it needs to compare two instantiations of that type.
The compiler takes your type, say Producer<T>, and instantiates it with two internal marker types. One marker is a subtype of the other. It then asks two structural questions:
- Is
Producer<Sub>assignable toProducer<Super>? - Is
Producer<Super>assignable toProducer<Sub>?
These are ordinary structural checks. The compiler looks inside the type, compares get(): Sub with get(): Super, and reports yes or no. The pair of answers is the measured variance of T. The result is cached for that type parameter.
The next table lists the outcomes.
| Result | Sub to Super | Super to Sub | Typical cause |
|---|---|---|---|
| Covariant | yes | no | `T` only in output positions |
| Contravariant | no | yes | `T` only in input positions of function-typed properties |
| Invariant | no | no | `T` in both input and output positions |
| Bivariant | yes | yes | `T` only in method parameters |
| Independent | yes | yes | `T` not used in the structure at all |
Bivariant and independent look the same to the two probes. Both accept either direction, but they get there differently. Bivariance comes from the loose method-parameter rule. Independence comes from T never being looked at.
Seeing the results
You can watch the measurement work by writing four small types and assigning them in both directions. The lines marked @ts-expect-error fail to compile, and the directive makes the compiler confirm that. If the line unexpectedly compiled, the directive itself would be an error.
// Compile with "strict": true (or "strictFunctionTypes": true)
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Producer<T> {
get(): T;
}
interface Sink<T> {
accept: (value: T) => void;
}
interface Cell<T> {
get(): T;
set: (value: T) => void;
}
interface Tagged<T> {
label: string;
}
declare const dogProducer: Producer<Dog>;
const p: Producer<Animal> = dogProducer; // covariant: Sub to Super works
declare const animalSink: Sink<Animal>;
const s: Sink<Dog> = animalSink; // contravariant: Super to Sub works
declare const dogCell: Cell<Dog>;
// @ts-expect-error Cell is invariant, so Sub to Super fails
const c1: Cell<Animal> = dogCell;
declare const animalCell: Cell<Animal>;
// @ts-expect-error Cell is invariant, so Super to Sub fails
const c2: Cell<Dog> = animalCell;
declare const taggedDog: Tagged<Dog>;
const t1: Tagged<Animal> = taggedDog; // T is unused: both directions work
declare const taggedAnimal: Tagged<Animal>;
const t2: Tagged<Dog> = taggedAnimal;Notice that Sink and Cell declare accept and set as function-typed properties. That choice matters, as a later section explains.
Probing with a type-level helper
You can ask the compiler the same questions without declaring variables. A conditional type returns true or false for any assignability question.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Producer<T> {
get(): T;
}
type IsAssignable<A, B> = [A] extends [B] ? true : false;
type Forward = IsAssignable<Producer<Dog>, Producer<Animal>>;
type Backward = IsAssignable<Producer<Animal>, Producer<Dog>>;
const forward: Forward = true;
const backward: Backward = false;The tuple wrappers [A] and [B] stop the conditional type from distributing over unions. This helper is handy when you want to document a type's variance in a test file.
Why the compiler measures at all
Measuring buys two things.
- Speed. Once the variance of
Tis known, comparingProducer<Dog>withProducer<Animal>only needs a comparison ofDogwithAnimal. The compiler skips re-walking every member. For large generic types, this shortcut is a large saving. - Termination on recursive types. A type such as
interface Tree<T> { value: T; children: Tree<T>[] }refers to itself. Comparing it member by member would loop back into the same comparison. A measured variance gives the compiler a way out.
The shortcut also changes what error messages say. A failed assignment may be reported against the type argument ("Animal is not assignable to Dog") instead of pointing at a specific member.
Where inference reads the wrong thing
Measurement is only as good as the structure it can see. Three situations deserve attention.
Methods are measured bivariantly
Method declarations keep the older bivariant parameter check, even under strictFunctionTypes. If you write accept(value: T): void as a method, the probes pass in both directions, and the measured result is bivariant, not contravariant. The compiler then accepts Consumer<Dog> where Consumer<Animal> is expected, which is unsafe. The Sink example above uses a function-typed property to get the strict result. Declaring in T fixes it for the method form as well, which a later chapter covers.
Adding a member changes the variance silently
Variance is a consequence of structure, so editing the structure edits the variance. Suppose a library ships this:
interface Source<T> {
get(): T;
}Every Source<Dog> is assignable to Source<Animal>. Now the author adds a write operation:
interface Source<T> {
get(): T;
set: (value: T) => void;
}T is now invariant, and every caller that relied on the old assignment stops compiling. Nothing in the source says "this was a breaking change". Explicit annotations exist to make that kind of change visible, because the annotation would then produce an error at the declaration instead of in downstream code.
Some constructs cannot be measured reliably
The marker-type experiment works well for plain object types, function types, and classes. It is less reliable for constructs where T flows through type-level computation, such as conditional types, mapped types with key remapping, and indexed access types. For these, the compiler marks the measured result as unreliable or unmeasurable. If the shortcut says "not assignable", it may fall back to a full structural comparison to confirm. The exact rules are an implementation detail and can change between compiler releases. Do not build code that depends on them.
Practical consequences
- You rarely need annotations for correctness. The inferred variance is already used for every assignability check.
- Declare function-typed properties when you want strictness. The choice between
handle: (a: T) => voidandhandle(a: T): voidchanges the measured variance understrictFunctionTypes. - Test the contract you care about. If a type's variance is part of your API, pin it with assignability tests like the ones above.
- Treat structure edits as potential breaking changes. Adding one member that uses
Tin the opposite position can flip covariant to invariant.
Exercises
Exercise
Under "strict": true, the compiler measures T in the interface below. Is it covariant, contravariant, invariant, bivariant, or independent? Explain which members drive the result. interface Handler<T> { current(): T; handle: (value: T) => void; }
Show answer
Invariant. The method current() returns T, an output position, so Handler<Dog> to Handler<Animal> would be safe on that member alone. The function-typed property handle takes T as a parameter, which strictFunctionTypes checks contravariantly, so that member only allows Handler<Animal> to Handler<Dog>. No single direction satisfies both members, so both probes fail and T is invariant.
Exercise
You change handle in the Handler interface above from a function-typed property to a method declaration: handle(value: T): void. What does the measured variance of T become, and why is that result a problem?
Show answer
T becomes covariant. The method parameter is checked bivariantly, so handle no longer blocks the Sub to Super direction, and current() allows it. The compiler now accepts Handler<Dog> where Handler<Animal> is expected, even though a caller could pass a Cat to handle on that Handler<Animal>, and the underlying Dog handler would receive a value it cannot handle. Declaring the type parameter as in out T would restore invariance by making the compiler check the declared variance against the structure.