Sub topic 11
Declaring invariance with in out
This chapter assumes you know the following:
- Generic interfaces and classes.
- Structural assignability.
- Covariance and contravariance, including the
outandinmodifiers from the previous chapters. - The
strictcompiler option.
TypeScript 4.7 or later is required for variance annotations.
What invariance means
A generic type is invariant in a type parameter when neither direction of assignment is accepted. Box<Dog> is not assignable to Box<Animal>, and Box<Animal> is not assignable to Box<Dog>. The type argument must match exactly, and subtyping between arguments does not carry over to the generic type.
The two examples in this chapter use the same subtype pair as the rest of the tutorial.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}Invariance appears when a type parameter is used in both input and output positions. A value of type T that you can read makes the type covariant. A value of type T that you can write makes it contravariant. Doing both leaves only exact matches.
The `in out` modifier
The in out modifier states invariance explicitly. It combines in (contravariant) and out (covariant), and the two constraints together permit only the identical type argument.
interface Box<in out T> {
get(): T;
set(value: T): void;
}
declare const dogBox: Box<Dog>;
declare const animalBox: Box<Animal>;
// @ts-expect-error: Box is invariant in T, so Box<Dog> is not a Box<Animal>
const a: Box<Animal> = dogBox;
// @ts-expect-error: invariant in both directions
const d: Box<Dog> = animalBox;The @ts-expect-error comments keep the file compiling while documenting that each line is rejected. If a line stopped producing an error, the compiler would report the unused directive.
Why both directions must fail
Each direction is blocked for a different reason, and you can trace each one to a single method.
Box<Dog> to Box<Animal> is unsafe because of set. If the assignment were allowed, you could call set(new Animal()) through the Box<Animal> view. The underlying box holds dogs, so it would now contain a plain Animal. A later get() through the original Box<Dog> reference would claim to return a Dog, and calling bark() on the result would fail at runtime.
Box<Animal> to Box<Dog> is unsafe because of get. The box may hold a plain Animal. Reading it through a Box<Dog> would hand back something typed as Dog that has no bark() method.
Covariance alone would allow the first assignment and contravariance alone would allow the second. A type parameter that appears in both positions cannot safely allow either.
A concrete class
Classes work the same way. This Cell stores one value and lets callers replace it.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
class Cell<in out T> {
constructor(private value: T) {}
get(): T {
return this.value;
}
set(value: T): void {
this.value = value;
}
}
const dogCell = new Cell<Dog>(new Dog());
// @ts-expect-error: Cell<Dog> is not assignable to Cell<Animal>
const animalCell: Cell<Animal> = dogCell;
const sameCell: Cell<Dog> = dogCell; // OK: identical type argument
console.log(sameCell.get().bark()); // woofThe last two lines show that invariance does not make the type unusable. It only forbids substituting a different instantiation.
Annotation versus inference
The compiler infers variance without any annotation, as the earlier chapter on inference described. In many cases in out only repeats what the compiler would work out anyway. The annotation matters most when inference gives a weaker answer than you want.
The clearest case is a method declaration. Method parameters are checked bivariantly even under strictFunctionTypes. This version of Box therefore infers differently from the one above.
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
}
interface StrictBox<in out T> {
get(): T;
set(value: T): void;
}
declare const looseDogs: LooseBox<Dog>;
declare const strictDogs: StrictBox<Dog>;
const loose: LooseBox<Animal> = looseDogs; // compiles, and is unsound
// @ts-expect-error: the annotation forces exact matching
const strict: StrictBox<Animal> = strictDogs;Because set is declared with method syntax, the compiler treats LooseBox<T> as covariant, and the unsafe assignment compiles. Adding in out forces the type arguments to be compared exactly, which closes the gap.
The same effect can be reached by changing set to a function-typed property, set: (value: T) => void. With strictFunctionTypes enabled, that makes the parameter contravariant and the whole type invariant by inference. The annotation is the better choice when you want the intent written down and do not want to rewrite the member syntax.
| Declaration | Variance the compiler uses | `Box<Dog>` to `Box<Animal>` | `Box<Animal>` to `Box<Dog>` |
|---|---|---|---|
| `<out T>` with `get(): T` | Covariant | Allowed | Rejected |
| `<in T>` with `accept(v: T): void` | Contravariant | Rejected | Allowed |
| `<in out T>` | Invariant | Rejected | Rejected |
| `<T>` with `get()` and method `set(v: T)` | Inferred covariant (bivariant parameter) | Allowed | Rejected |
Annotating a stricter variance than the structure needs
An in out annotation is always accepted, even if the type uses T in only one position. The compiler checks that the annotation is no weaker than the structure requires. It does not check that the annotation is as weak as possible. Invariance is the strictest relationship, so every structure satisfies it.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface ReadOnlyHandle<in out T> {
get(): T;
}
declare const dogHandle: ReadOnlyHandle<Dog>;
// @ts-expect-error: declared invariant even though T only appears in output position
const animalHandle: ReadOnlyHandle<Animal> = dogHandle;Without the annotation, ReadOnlyHandle<Dog> would be assignable to ReadOnlyHandle<Animal>. Declaring in out here is a deliberate choice to forbid that. Reasons to do it include:
- You plan to add a write method later and want the current API to behave the way the final one will.
- The type represents an identity or a resource slot, where substituting a related type would be a logic error even if no write exists today.
The annotation is a promise to callers, so do not add it without a reason. Every use of the type becomes stricter, and callers who relied on substitution will see new errors.
Syntax details
- Write the modifiers in the order
in out. The reverse order,out in, is a compile error. - The modifiers go directly before the type parameter name, with any
extendsconstraint after it, as ininterface Store<in out T extends Animal>. - With several parameters, annotate each one separately:
interface Mapper<in I, out O>. - Annotating one parameter does not affect the others. Parameters without an annotation are still inferred.
Common mistakes
- Assuming
in outis the default. Unannotated parameters get whatever variance the structure implies, which may be covariant, contravariant, bivariant, or invariant. Only the annotation guarantees invariance. - Expecting
in outto change runtime behavior. The modifiers exist only at compile time. They are erased from the emitted JavaScript, and they do not stop a value from being mutated unsafely through ananycast. - Forgetting that arrays bypass the check.
Dog[]is assignable toAnimal[]because arrays are treated covariantly. A wrapper you declare within outis stricter than the built-in array, so do not use the array as a model for what invariance looks like. - Annotating
in outon a type that never needs it. A purely read-only type is usually better asout, because it lets callers passProducer<Dog>whereProducer<Animal>is expected.
Summary of the decision
Use in out when a type parameter is read and written, when you want the compiler to reject substitution even if the structure would allow it, or when method syntax would otherwise make a mutable type look covariant. Use out or in when only one direction is needed. Leave the parameter unannotated when inference already gives the right answer and you have no reason to pin it.
Exercise
An interface is declared as interface Slot<T> { read(): T; write(value: T): void; } using method syntax, and with strictFunctionTypes enabled. Is Slot<Dog> assignable to Slot<Animal>? What single change makes the compiler reject that assignment, and why does the change work?
Show answer
Yes, it is assignable. Method parameters stay bivariant even under strictFunctionTypes, so the compiler infers T as covariant and accepts the unsafe assignment. Changing the declaration to interface Slot<in out T> makes the compiler compare the type arguments invariantly, so Slot<Dog> is no longer assignable to Slot<Animal>. Changing write to a function-typed property, write: (value: T) => void, would also work, because strictFunctionTypes then checks the parameter contravariantly.
Exercise
Is interface Tag<in out T> { value: T; } a compile error because T only appears in an output position? What is the effect of the annotation on Tag<Dog> and Tag<Animal>?
Show answer
It is not an error. An in out annotation is always accepted, since invariance is the strictest relationship. The effect is that Tag<Dog> and Tag<Animal> are not assignable to each other in either direction, although without the annotation Tag<Dog> would be assignable to Tag<Animal>.