Sub topic 4
Invariance: Types That Both Read and Write
Prerequisites: You should understand TypeScript generics, interfaces, structural typing, and basic assignability. You should also know that Dog is a subtype of Animal when every Dog can be used where an Animal is expected.
The problem with a mutable generic type
Variance describes how a relationship between type arguments affects a relationship between generic types. If Dog is assignable to Animal, you might ask whether Box<Dog> is assignable to Box<Animal>.
For a type that both produces and consumes values, neither direction is safe. Such a type is invariant in its type parameter.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Box<in out T> {
get(): T;
set(value: T): void;
}
function makeDogBox(): Box<Dog> {
let current = new Dog();
return {
get() {
return current;
},
set(value) {
current = value;
}
};
}
const dogBox: Box<Dog> = makeDogBox();
// Neither assignment is safe:
// const animals: Box<Animal> = dogBox;
// const dogs: Box<Dog> = animals;get reads a value of type T, so T appears in an output position. set receives a value of type T, so T appears in an input position. The two uses require opposite variance directions.
Why covariance is unsafe
Suppose TypeScript allowed this assignment:
const animals: Box<Animal> = dogBox;The variable animals would appear to accept every Animal. Someone could then write an ordinary Animal into it:
animals.set(new Animal());However, the original object is still a Box<Dog>. Reading from dogBox could now produce an Animal that has no bark method.
This is why a mutable box cannot safely be covariant.
Why contravariance is unsafe
The opposite assignment is also unsafe:
const animalBox: Box<Animal> = {
get: () => new Animal(),
set: () => {}
};
// const dogs: Box<Dog> = animalBox;If this were allowed, the variable dogs would promise that get() always returns a Dog. But the actual box can return an ordinary Animal. Calling bark() on that result would be invalid.
The two directions fail for different reasons:
| Assignment | What could go wrong |
|---|---|
| `Box<Dog>` to `Box<Animal>` | A non-Dog `Animal` could be written into the box |
| `Box<Animal>` to `Box<Dog>` | A returned `Animal` might not have `Dog` members |
Therefore, Box<Dog> and Box<Animal> are unrelated for assignability purposes, even though Dog is assignable to Animal.
Declaring invariance with `in out`
The in out modifier documents that a type parameter is invariant:
interface Box<in out T> {
get(): T;
set(value: T): void;
}The modifier tells TypeScript that T must be used invariantly. TypeScript checks the annotation against the structure of the type. A type parameter marked in out must support both input and output use.
A type can be invariant without an explicit annotation when the compiler infers invariance from its members. The annotation makes the design intent visible and can prevent later changes from accidentally weakening the intended relationship.
A practical design rule
Separate operations when possible:
- A producer that only returns
Tcan be covariant. - A consumer that only accepts
Tcan be contravariant. - A type that both returns and accepts
Tshould be invariant. - A read-only container is often safer than a mutable container.
Exercise
Why is Box<Dog> not safely assignable to Box<Animal> when Box has both get() and set()?
Show answer
The wider Box<Animal> view could write an ordinary Animal into the same object. A later read through Box<Dog> would then produce a value that is not necessarily a Dog.