Sub topic 15
Variance annotations with in and out
This chapter assumes you know the following:
- How covariance, contravariance and invariance work for function parameters and return types.
- How
strictFunctionTypestreats method syntax. - How the compiler compares generic types such as
Array<Dog>andArray<Animal>.
Here you will learn how to state a type parameter's variance yourself instead of letting the compiler work it out.
What the annotations say
By default, TypeScript measures the variance of each type parameter. It compares two instantiations of a generic type, such as Box<Dog> and Box<Animal>, and records which direction of assignment succeeds. Since TypeScript 4.7 you can write that result into the declaration with the in and out modifiers.
| Annotation | Variance | Meaning | Allowed assignment |
|---|---|---|---|
| `out T` | Covariant | `T` only comes out, as return types or readable properties | `Foo<Dog>` to `Foo<Animal>` |
| `in T` | Contravariant | `T` only goes in, as parameters | `Foo<Animal>` to `Foo<Dog>` |
| `in out T` | Invariant | `T` goes both in and out | Neither direction |
| none | Measured | The compiler infers it from the structure | Depends on the structure |
The mnemonic is the data flow. A producer hands out values of T, so out fits. A consumer accepts values of T, so in fits.
Declaring and using them
Here is a covariant producer and a contravariant consumer. The consumer uses a function-typed property so that strictFunctionTypes checks its parameter contravariantly.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface Producer<out T> {
get(): T;
}
interface Consumer<in T> {
set: (value: T) => void;
}
declare let dogProducer: Producer<Dog>;
declare let animalProducer: Producer<Animal>;
animalProducer = dogProducer; // OK: out T is covariant
dogProducer = animalProducer; // Error: Animal is not assignable to Dog
declare let dogConsumer: Consumer<Dog>;
declare let animalConsumer: Consumer<Animal>;
dogConsumer = animalConsumer; // OK: in T is contravariant
animalConsumer = dogConsumer; // Error: a Dog consumer cannot accept every AnimalA type parameter that is both read and written should be invariant.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface Box<in out T> {
get(): T;
set: (value: T) => void;
}
declare let dogBox: Box<Dog>;
declare let animalBox: Box<Animal>;
animalBox = dogBox; // Error: a Dog box cannot safely accept any Animal
dogBox = animalBox; // Error: get() might return an Animal that is not a DogThe compiler checks your claim
An annotation is a claim about the structure, and the compiler verifies it. If the body uses T in a way that contradicts the annotation, the declaration is an error.
interface Wrong<out T> {
set: (value: T) => void; // Error: T is used in a position that makes it contravariant
}Annotations are therefore not casts. You can't use them to make an unsafe type look safe. You can only restrict a type parameter more than the structure requires. For example, in out T on a type that is structurally covariant is allowed, and it makes the type stricter.
Why write them
Writing annotations has three uses.
- Documentation of intent.
Producer<out T>tells a reader thatTis read-only data flow. If someone later adds a method that acceptsT, the compiler reports an error at the declaration, not at some distant call site. - Performance. When the compiler compares
Foo<A>withFoo<B>, it normally measures variance first by comparing marker instantiations structurally. With an annotation it can use your declaration and skip the measurement. This helps most with large or deeply recursive generic types, where measurement is expensive. - Correcting a poor measurement. For some recursive types the measured variance is unreliable, and the compiler falls back to a slower structural comparison. An explicit annotation gives the compiler a definite answer.
Use annotations where one of these applies. For a small type that is used a few times, inference already gives the correct result.
Gotchas
Annotations are allowed only on the type parameters of interfaces, classes and type aliases. For type aliases, the aliased type must be an object, function, constructor or mapped type. You can't annotate a type parameter on a function declaration.
Method syntax interacts with annotations. Method parameters are compared bivariantly even under strictFunctionTypes, so a method such as handle(value: T): void doesn't contradict out T. The compiler does not reject it, but you lose the safety the annotation suggests.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface LooseSource<out T> {
get(): T;
accept(value: T): void; // method syntax: bivariant, so no error here
}
interface StrictSource<out T> {
get(): T;
accept: (value: T) => void; // Error: property syntax is checked contravariantly
}If you want an annotation to enforce your intent, declare parameter positions with function-typed properties. Readonly properties and getters suit out.
Annotations also affect only generic type comparison. They don't change how a single non-generic type is compared with another.
Choosing an annotation
Follow these steps to decide:
- Look at every use of
Tinside the type. - If
Tappears only in return types or readonly properties, useout. - If
Tappears only in parameters of function-typed properties, usein. - If
Tappears in both kinds of position, usein out, or leave the parameter unannotated. - If the type is large or recursive and comparisons are slow, add the annotation even when inference would find the same answer.
Exercise
Given interface Logger<T> { log: (value: T) => void }, which annotation should T have, and which assignment between Logger<string> and Logger<string | number> compiles afterwards?
Show answer
Use in T, because T appears only as a parameter of a function-typed property. A Logger<string | number> can handle every string, so Logger<string | number> is assignable to Logger<string>. The reverse fails, because a Logger<string> cannot accept numbers.
Exercise
Why does interface Handler<out T> { handle(value: T): void } compile, while interface Handler<out T> { handle: (value: T) => void } does not?
Show answer
Method syntax is compared bivariantly, so the parameter position does not contradict covariance. The property form is compared contravariantly under strictFunctionTypes, so using T as a parameter contradicts out T and the compiler reports an error.