Sub topic 2
Covariance: types that produce values
This chapter assumes you know TypeScript generics, interfaces, classes and function types, and structural assignability. It also assumes you compile with "strict": true. You will learn what covariance means, how to spot a covariant type parameter, and how the out modifier states it.
Subtyping is the starting point
Variance describes how a relationship between two type arguments carries over to the generic types built from them. The tutorial uses one pair throughout: Dog is a subtype of Animal, so a Dog value can go wherever an Animal is expected.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dog: Dog = new Dog();
const animal: Animal = dog; // OK: Dog is a subtype of Animal
// const backToDog: Dog = animal; // Error: Animal lacks bark()Assignability runs one way, from subtype to supertype. The question for a generic type such as Producer<T> is whether Producer<Dog> can be used where Producer<Animal> is expected.
What covariance means
A generic type is covariant in T when the direction of assignability is preserved. If Dog is assignable to Animal, then Producer<Dog> is assignable to Producer<Animal>. The subtype relationship points the same way before and after wrapping, and "co" means "together with".
Why producers are safe to widen
Think about what a consumer of a Producer<Animal> does. It calls get() and receives something it treats as an Animal. It can only read the value as an Animal. If the real producer hands back a Dog, nothing breaks, because every Dog is an Animal.
interface Producer<out T> {
get(): T;
}
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer; // OK: covariant
// declare const anyAnimalProducer: Producer<Animal>;
// const d: Producer<Dog> = anyAnimalProducer; // Error: direction is not reversibleThe first assignment is safe because the caller of animalProducer.get() expects at most an Animal, and a Dog satisfies that.
The reverse is unsafe. A Producer<Animal> may return a plain Animal or some other subtype such as a Cat. A caller holding it as Producer<Dog> would call .bark() on something that cannot bark.
The rule: when a value flows out of a type to its users, the type can be treated as the more general version. This is why covariant positions are called output positions.
Recognizing output positions
You classify a type parameter by looking at where it appears. These positions are covariant:
- The return type of a method or function:
get(): T. - A
readonlyproperty:readonly value: T. - A getter-only accessor.
- A type argument of another covariant type, such as
Promise<T>orReadonlyArray<T>, used in an output position.
A short example puts several of these together:
interface Shelter<out T> {
readonly resident: T;
adopt(): T;
adoptLater(): Promise<T>;
}
declare const dogShelter: Shelter<Dog>;
const animalShelter: Shelter<Animal> = dogShelter; // OK: T only appears in outputsEvery use of T here sits in an output position, so Shelter is covariant in T.
Function types follow the same rule for their return types. A function that returns a Dog can stand in for a function that returns an Animal:
declare const makeDog: () => Dog;
const makeAnimal: () => Animal = makeDog; // OK: return types are covariantThe following table summarizes how the position of T decides its variance. This chapter covers only the first row. The remaining rows are covered in the next chapters.
| Where `T` appears | Variance | Example |
|---|---|---|
| Only outputs (return types, readonly data) | Covariant | `get(): T` |
| Only inputs (parameters) | Contravariant | `accept(value: T): void` |
| Both inputs and outputs | Invariant | `get(): T` and `set(value: T): void` |
Declaring covariance with out
TypeScript 4.7 added optional variance annotations. Writing out before a type parameter states that the type parameter is covariant. It is the first line of Producer<out T> above. The keyword out is easy to remember because covariant parameters only let values come out.
Without the annotation, the compiler still works out the variance by examining the structure of the type. Both of these declarations behave the same way for assignments:
interface ImplicitProducer<T> {
get(): T;
}
interface ExplicitProducer<out T> {
get(): T;
}
declare const dogImplicit: ImplicitProducer<Dog>;
declare const dogExplicit: ExplicitProducer<Dog>;
const a: ImplicitProducer<Animal> = dogImplicit; // OK: inferred covariant
const b: ExplicitProducer<Animal> = dogExplicit; // OK: declared covariantThe annotation adds three things. It documents the intent for readers of the code. It makes the compiler check that the intent holds (the next section shows how). It lets the compiler skip measuring variance for that parameter.
The compiler checks your claim
An out annotation is a promise, and the compiler verifies it against the declaration. If T appears in an input position, the promise is false and the compiler reports an error:
// Compile with "strict": true (or "strictFunctionTypes": true)
interface Writer<out T> {
write: (value: T) => void; // Error: T is used in an input position, which contradicts out
}Here write is a function-typed property whose parameter uses T. That makes T contravariant, which conflicts with out. The error message says that the type is not covariant in T as annotated. To fix it, remove out if inference gives the variance you want, or use in if the type really consumes values. The in modifier is the subject of a later chapter.
The check depends on strictFunctionTypes. With it off, the compiler checks function parameters bivariantly, so the declaration above would not be flagged. Keep "strict": true on so annotations are verified.
Covariance in practice: read-only views
Covariance is the reason you can pass narrower collections to code that only reads them. A function that prints animals should accept a list of dogs:
function describeAll(items: ReadonlyArray<Animal>): string[] {
return items.map((item) => item.name);
}
const dogs: Dog[] = [new Dog(), new Dog()];
console.log(describeAll(dogs)); // ["animal", "animal"]ReadonlyArray<Dog> is assignable to ReadonlyArray<Animal> because it has no way to put anything in. This is the safe version of a covariant collection. A later chapter covers why the mutable Dog[] is also accepted by TypeScript and why that is a hole in the type system.
Designing for covariance
When you write a generic type that only hands out values, you get the most flexible assignability by keeping T out of input positions. These habits help:
- Return
Tfrom methods and make datareadonly. - Take configuration or callbacks in the constructor, not in methods, when you can. Constructor parameters are not part of the instance type, so they do not affect its variance.
- Add
outon public types so that an accidental input position, such as a newsetmethod, causes a compile error instead of quietly changing how the type can be assigned.
The third habit is the main reason to annotate. Without out, adding reset(value: T): void to a published interface changes its inferred variance. Code elsewhere that assigned Producer<Dog> to Producer<Animal> could then stop compiling, and the error would appear at the use site. With out, the error appears on the declaration you just edited.
Common mistakes
- Assuming covariance runs both ways.
Producer<Dog>goes toProducer<Animal>, never the reverse. - Adding
outto a type that stores values it receives. A method such asset(value: T)is an input position, and the annotation will be rejected understrictFunctionTypes, or in some forms silently accepted for methods. Usein outif the type truly reads and writes. - Reading variance from the name.
Produceris covariant because of its members, not its name. Always check whereTappears.
Exercise
Given interface Source<out T> { next(): T; peek(): T | undefined; } and declare const dogs: Source<Dog>;, is const animals: Source<Animal> = dogs; allowed? Is declare const a: Source<Animal>; const d: Source<Dog> = a; allowed? Explain both answers using output positions.
Show answer
The first assignment is allowed. T appears only in return types (next(): T and peek(): T | undefined), which are output positions, so Source is covariant and Source<Dog> is assignable to Source<Animal>. The second assignment is an error. A Source<Animal> might produce a plain Animal or a Cat, and a holder of Source<Dog> would expect every result to be a Dog with a bark() method.
Exercise
Why does this declaration fail to compile under "strict": true, and what are two ways to fix it? interface Sink<out T> { push: (value: T) => void; }
Show answer
T is the parameter of a function-typed property, which is an input position, so T is contravariant. That contradicts the out annotation. Fix it either by changing the annotation to in, which states the real variance of a type that consumes values, or by restructuring the type so that T only appears in outputs, for example by returning values instead of accepting them.