Sub topic 4
Invariance: types that both read and write
This chapter assumes you know generic interfaces and classes, structural assignability, and the strict compiler option. It also assumes you have seen covariance (out) and contravariance (in) from the previous chapters. Here you will see what happens when a single type parameter does both jobs.
The problem: one parameter, two directions
A covariant type only produces values of T, so it can be widened: Producer<Dog> is assignable to Producer<Animal>. A contravariant type only consumes values of T, so the direction flips: Consumer<Animal> is assignable to Consumer<Dog>.
Many real types do both. A mutable cell, a cache entry, a state container, and a two-way binding all hand out a T and accept a T. The two rules then contradict each other. The read side demands the covariant direction. The write side demands the contravariant direction. The only assignment that satisfies both is the one where the type arguments are identical.
A type parameter that is constrained in both directions is invariant. Box<Dog> and Box<Animal> are unrelated for assignability, even though Dog is a subtype of Animal.
Why both directions are unsafe
Consider this interface, which uses the Animal and Dog classes from earlier chapters.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Box<in out T> {
get(): T;
set(value: T): void;
}
declare const dogBox: Box<Dog>;
declare const animalBox: Box<Animal>;
// const a: Box<Animal> = dogBox; // Error: Box is invariant in T
// const d: Box<Dog> = animalBox; // Error: Box is invariant in TEach error protects a different operation.
Why Box<Dog> cannot become Box<Animal>. Suppose the assignment were allowed. Code holding the Box<Animal> view could call set(new Animal()). The underlying box still belongs to the dog view, so the next dogBox.get().bark() would call a method that does not exist. The unsafe step is the write.
Why Box<Animal> cannot become Box<Dog>. Suppose this assignment were allowed. Code holding the Box<Dog> view could call get().bark(). The underlying box might contain a plain Animal, so bark would be missing at runtime. The unsafe step is the read.
Invariance rejects both assignments, so the only safe way to share a Box<Dog> is to keep treating it as a Box<Dog>.
A runnable implementation
The following program uses a concrete implementation of the box. It compiles under strict.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Box<in out T> {
get(): T;
set(value: T): void;
}
function makeBox<T>(initial: T): Box<T> {
let value = initial;
return {
get: () => value,
set: (next) => {
value = next;
},
};
}
const dogBox: Box<Dog> = makeBox(new Dog());
console.log(dogBox.get().bark()); // woof
dogBox.set(new Dog()); // OK: the argument is a Dog
// dogBox.set(new Animal()); // Error: Animal lacks bark()The box type is still useful. You can create Box<Dog> values and read and write them freely. You just cannot pass one where a Box<Animal> is expected.
Invariance without any annotation
You do not need in out to get an invariant type. The compiler measures variance by checking how T is used, and it reaches the same answer when the write side is a function-typed property.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
// Compile with "strict": true (or "strictFunctionTypes": true)
interface Store<T> {
get: () => T;
set: (value: T) => void;
}
declare const dogStore: Store<Dog>;
declare const animalStore: Store<Animal>;
// const a: Store<Animal> = dogStore; // Error: 'set' parameter is checked contravariantly
// const d: Store<Dog> = animalStore; // Error: 'get' return type is checked covariantlyHere get forces covariance and set forces contravariance. Together they leave only the identical type arguments.
The method-declaration trap
The previous chapters showed that strictFunctionTypes checks parameters of function-typed properties contravariantly, while method declarations stay bivariant. This changes the result for Box. Write it without any annotation:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface LooseBox<T> {
get(): T;
set(value: T): void; // method syntax: parameter is bivariant
}
declare const dogBox: LooseBox<Dog>;
const animalBox: LooseBox<Animal> = dogBox; // Compiles, and is unsound
animalBox.set(new Animal()); // dogBox now holds a non-DogBecause set is declared as a method, its parameter is compared bivariantly. The compiler sees T as covariant through get and tolerant in set, so it infers covariance. The assignment compiles, and the unsafe write goes through.
LooseBox<T> is not truly invariant. It is invariant only in intent. Adding the annotation fixes this:
interface Box<in out T> {
get(): T;
set(value: T): void;
}With in out, the compiler stops using the measured result and treats T as invariant when it compares Box<Dog> and Box<Animal>. This is the main practical reason to write in out. It restores the safety that method syntax gives up.
Classifying a type parameter
Use these rules when you read a generic type. Look at every place T appears.
| Where `T` appears | Variance | Annotation |
|---|---|---|
| Return types, readonly properties | Covariant | `out T` |
| Parameter types of function-typed properties | Contravariant | `in T` |
| Both of the above | Invariant | `in out T` |
| Mutable property of type `T` | Invariant | `in out T` |
| Parameter of a method declaration only | Bivariant when inferred | Annotate to fix intent |
A mutable property such as value: T counts as both. Reading it is an output and assigning to it is an input. TypeScript's own property check is covariant, so an unannotated interface with value: T is still treated as covariant. This is the same unsoundness you saw with arrays. If you want the safe behavior, declare in out.
interface Ref<in out T> {
value: T;
}With this annotation, Ref<Dog> is not assignable to Ref<Animal>, which matches what the property can really do.
The cost of invariance and how to work around it
Invariance is strict, and sometimes you want only one capability. If a function only reads, ask for a read-only view. Split the interface so each half has the variance it needs:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Source<out T> {
get(): T;
}
interface Sink<in T> {
set(value: T): void;
}
interface Box<in out T> extends Source<T>, Sink<T> {}
function describe(source: Source<Animal>): string {
return source.get().name;
}
declare const dogBox: Box<Dog>;
console.log(describe(dogBox)); // OK: Box<Dog> is a Source<Dog>, and Source is covariantdescribe accepts any Source<Animal>, so it can take a Box<Dog> through its read-only face. The function cannot write, so nothing unsafe can happen. Prefer this approach to loosening a type to any or adding casts.
Checking your understanding
Exercise
Given interface Counter<T> { current(): T; reset(value: T): void; } with no annotations, and declare const c: Counter<Dog>, does const a: Counter<Animal> = c; compile under strict? What change would make the compiler reject it, and why would you want that?
Show answer
It compiles, because both members use method syntax. Method parameters are bivariant, so the compiler infers T as covariant. This is unsound, since a.reset(new Animal()) would put an Animal into a counter that c still treats as a Counter<Dog>. Changing the declaration to interface Counter<in out T> makes T invariant, so the assignment fails. Rewriting reset as the property reset: (value: T) => void also makes it fail under strictFunctionTypes.
Exercise
A function function show(b: Box<Animal>): void only calls b.get(). How can you let callers pass a Box<Dog> without weakening Box?
Show answer
Change the parameter type to a read-only covariant interface such as Source<Animal>, which declares Source<out T> { get(): T }. A Box<Dog> is assignable to Source<Animal> because Box<Dog> extends Source<Dog> and Source is covariant. The function can no longer write, so the invariant Box stays strict everywhere else.