Sub topic 9
Declaring covariance with out
This chapter assumes you know TypeScript generics, interfaces, classes, function types, and structural typing. It also assumes you compile with strict enabled. The out modifier needs TypeScript 4.7 or later. It builds on the Animal and Dog classes from earlier chapters, where Dog extends Animal.
What out states
A generic type is covariant in a type parameter when subtyping between the arguments carries over in the same direction. Because Dog is assignable to Animal, a covariant Producer<Dog> is assignable to Producer<Animal>.
The compiler already works this out by inspecting how the type uses its parameter. The out modifier lets you state the result yourself. You write it in front of the type parameter:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Producer<out T> {
get(): T;
}
const dogProducer: Producer<Dog> = { get: () => new Dog() };
const animalProducer: Producer<Animal> = dogProducer; // OK: covariant
console.log(animalProducer.get().name); // "animal"The word out refers to values leaving the type. A Producer<T> only hands out values of type T, so a Producer<Dog> can stand in anywhere a Producer<Animal> is expected. Every value it returns is a Dog, and every Dog is an Animal.
The direction cannot be reversed. A Producer<Animal> may return a plain Animal, so it is not a Producer<Dog>.
Where T may appear under out
An out annotation is a promise that T appears only in output positions. The most common output position is a return type. There are others, and one of them surprises people.
| Position of `T` | Compatible with `out`? | Reason |
|---|---|---|
| Method return type, `get(): T` | Yes | Values flow out to the caller |
| Function property return type, `get: () => T` | Yes | Same reason |
| `readonly` property, `readonly value: T` | Yes | Callers can only read it |
| Parameter of a callback parameter, `subscribe: (cb: (v: T) => void) => void` | Yes | Two input positions cancel out |
| Parameter of a function-typed property, `write: (v: T) => void` | No | Values flow in, so `T` is contravariant |
| Parameter of a method, `write(v: T): void` | Not caught | Method parameters stay bivariant |
The callback row works like a double negative. The subscribe function takes a listener, and the listener takes a T. The listener is the one that receives the value, but you supply it, and so the value flows out of the object toward your code.
interface Subscribable<out T> {
subscribe: (listener: (value: T) => void) => void;
}
const dogs: Subscribable<Dog> = {
subscribe: (listener) => listener(new Dog()),
};
const animals: Subscribable<Animal> = dogs; // OK
animals.subscribe((a) => console.log(a.name));Classes, aliases, and constraints
out is not limited to interfaces. You can put it on class type parameters and on type aliases. It goes before the parameter name, and a constraint or default goes after the name:
class Source<out T extends Animal = Animal> {
constructor(private readonly items: readonly T[]) {}
first(): T | undefined {
return this.items[0];
}
}
type Thunk<out T> = () => T;
const dogSource: Source<Dog> = new Source([new Dog()]);
const animalSource: Source<Animal> = dogSource; // OK
const dogThunk: Thunk<Dog> = () => new Dog();
const animalThunk: Thunk<Animal> = dogThunk; // OKPrivate members count as well. The items field is private readonly, and it still must be consistent with the annotation. A readonly array of T is covariant, so it passes.
You can annotate each parameter independently. A type with several parameters might mix modifiers, for example interface Handler<out Result, in Input>. The in modifier is the subject of the next chapter.
The mutable property surprise
You may expect a plain mutable property to be an input position, because code can write to it. TypeScript does not treat it that way. Property reads and writes are both checked covariantly, which is a deliberate unsoundness:
interface Cell<out T> {
value: T; // Compiles: mutable properties are checked covariantly
}
const dogCell: Cell<Dog> = { value: new Dog() };
const animalCell: Cell<Animal> = dogCell; // OK
animalCell.value = new Animal(); // Compiles, but dogCell.value is no longer a DogThis is the same hole as array covariance, which a later chapter covers. The modifier does not fix it for you. If you want a guarantee that nobody writes through the widened reference, mark the property readonly:
interface SafeCell<out T> {
readonly value: T;
}The out annotation checks what the compiler can measure. It does not make an unsound type sound.
What the compiler checks
When you write out T, the compiler verifies the claim. It compares two instantiations of the type, one with a subtype argument and one with a supertype argument. It then confirms that the subtype version is assignable to the supertype version. If the check fails, you get an error on the declaration.
interface Writer<out T> {
write: (value: T) => void; // Error: T is used in an input position, which contradicts out
}Under strictFunctionTypes, the parameter of a function-typed property is checked contravariantly. That makes Writer<Dog> not assignable to Writer<Animal>, so the out claim is false.
There are two ways to fix this error. If the type really does consume values, change the annotation to in (or in out if it also produces them). If the type should only produce values, remove the input position.
Without strictFunctionTypes, parameters are compared bivariantly. The same annotation may then compile without complaint, because the compiler cannot find a contradiction. This is another reason to keep strict on.
Why write out at all
The compiler infers variance, so the annotation is usually redundant. It earns its place in a few situations.
- Intent and review. The annotation documents the design. If a later edit adds an input position, the build fails at the declaration. Without the annotation, the type would silently become invariant. Code that assigned
Producer<Dog>toProducer<Animal>would then fail somewhere far from the edit. - Recursive and mutually recursive types. The compiler sometimes cannot settle the variance of a type that refers to itself and gives a wrong or unhelpful answer. An explicit
outremoves the guesswork. - Performance. With an annotation, the compiler can compare
Producer<Dog>andProducer<Animal>by comparing the arguments. Otherwise it may need to compare members structurally. This matters for large or deeply nested generic types.
A final point concerns scope. The modifier changes only compile-time checking. It is erased from the emitted JavaScript and does not change what any value can do at runtime.
Putting it together
A realistic use is a read-only result type. Both parameters only produce values, so both can be marked out:
interface Result<out Value, out Err> {
readonly ok: boolean;
unwrap(): Value;
error(): Err | undefined;
}
function describe(result: Result<Animal, Error>): string {
return result.ok ? result.unwrap().name : "failed";
}
declare const dogResult: Result<Dog, TypeError>;
describe(dogResult); // OK: Dog is an Animal, and TypeError is an ErrorBecause Result is covariant in both parameters, describe accepts any result whose value is an Animal subtype and whose error is an Error subtype.
Exercise
Under "strict": true, which of these declarations produce a compile error? Explain each answer. (a) interface A<out T> { get: () => T } (b) interface B<out T> { put: (value: T) => void } (c) interface C<out T> { watch: (cb: (value: T) => void) => void }
Show answer
Only (b) fails. In (a), T appears only as a return type, which is an output position. In (b), T is the parameter of a function-typed property, which strictFunctionTypes checks contravariantly, so B<Dog> is not assignable to B<Animal> and the out claim is false. In (c), T is the parameter of a callback that is itself a parameter, and two input positions cancel, so T is covariant and out is correct.