Sub topic 10
Declaring contravariance with in
This chapter assumes you know TypeScript generics, interfaces, classes and function types. It also assumes you understand structural assignability and compile with strict enabled. Earlier chapters showed that a type parameter used only for input is contravariant. Here you will state that fact in code with the in modifier (TypeScript 4.7+) and let the compiler enforce it.
The setup: Animal and Dog
The examples reuse the same subtype pair as earlier chapters.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}Dog is a subtype of Animal, so a Dog can go anywhere an Animal is expected. The reverse is not allowed.
What `in` says
An in modifier on a type parameter declares it contravariant. The type only consumes values of T and never hands them back out. Place the modifier directly before the parameter name.
interface Consumer<in T> {
accept(value: T): void;
}
const animalConsumer: Consumer<Animal> = {
accept(value) {
console.log(`accepted ${value.name}`);
},
};
// Direction reverses: Consumer<Animal> is assignable to Consumer<Dog>.
const dogConsumer: Consumer<Dog> = animalConsumer;
dogConsumer.accept(new Dog());A Consumer<Animal> can handle any animal, so it can handle dogs. Anything that needs a Consumer<Dog> is safe with it.
The opposite direction fails:
// declare const onlyDogs: Consumer<Dog>;
// const c: Consumer<Animal> = onlyDogs; // Error: it could receive a non-DogSomeone holding a Consumer<Animal> may pass a cat. A consumer built for dogs cannot take one.
Reading the rule from the position of T
Use this check when you classify a parameter as contravariant.
| Where `T` appears | Variance it demands |
|---|---|
| Return type, readonly property | covariant (`out`) |
| Parameter of a function-typed property or function type | contravariant (`in`) |
| Both of the above | invariant (`in out`) |
| Nowhere | no constraint |
For in, every use of T must be an input. Parameters of callbacks count as inputs, with one catch. A callback parameter inside a parameter flips twice, so T there ends up in an output position.
interface Subscriber<in T> {
// T is a parameter of a function that is itself a parameter of
// a function type, so the two flips cancel out here.
onEvent(handler: (value: T) => void): void;
}This declaration is wrong. Subscriber<T> receives a handler that gets values of T, which means the subscriber produces T values. It is covariant, and the annotation in contradicts it. Count the flips before you write the modifier.
A practical case: comparers
Sorting is a common use. A comparison function only consumes the values it compares.
type Comparer<in T> = (a: T, b: T) => number;
const byName: Comparer<Animal> = (a, b) => a.name.localeCompare(b.name);
const dogs: Dog[] = [new Dog(), new Dog()];
const dogComparer: Comparer<Dog> = byName; // OK: contravariant
dogs.sort(dogComparer);A general comparer for animals sorts dogs correctly, so code asking for a Comparer<Dog> accepts it. The same pattern covers validators, serializers, loggers, event handlers and anything else shaped like "give me a T and I'll do something with it".
Why `in` works for function types and properties
Under strictFunctionTypes, function-typed properties and function type aliases check their parameters contravariantly. This matches the in modifier exactly.
// Compile with "strict": true (or "strictFunctionTypes": true)
interface Handler<in T> {
handle: (value: T) => void;
}
declare const animalHandler: Handler<Animal>;
const dogHandler: Handler<Dog> = animalHandler; // OKMethods behave differently. A method declaration such as accept(value: T): void keeps the older bivariant parameter check. in is still valid there, because the contravariant direction passes. The weaker check shows up when you write the wrong annotation instead.
// Compile with "strict": true (or "strictFunctionTypes": true)
interface MethodWriter<out T> {
write(value: T): void; // Accepted: method parameters are bivariant
}
interface PropertyWriter<out T> {
write: (value: T) => void; // Error: T is in an input position
}The out annotation on MethodWriter is accepted even though T is used as an input. The bivariant method check lets it through. The compiler rejects the property form.
Combining `in` with other parameters
Each type parameter gets its own modifier. A transformer that takes I and returns O is contravariant in one and covariant in the other.
interface Transformer<in I, out O> {
transform: (input: I) => O;
}
declare const describe: Transformer<Animal, string>;
const dogDescribe: Transformer<Dog, string> = describe; // OK: I is contravariantIf one parameter is used in both directions, write in out. The next chapter covers that case.
What happens when `in` is wrong
The compiler checks every annotation against the structure of the type. It compares instantiations that use marker subtype and supertype arguments, and it reports an error when the annotated direction does not hold. The error says the type is "not assignable ... as implied by variance annotation".
// Compile with "strict": true (or "strictFunctionTypes": true)
interface Source<in T> {
get: () => T; // Error: T is in an output position, which contradicts in
}The fix is to change the annotation or the type.
- If
Tis truly output only, useout Tinstead. - If the type must both read and write
T, usein out T. - If the type should only consume
T, remove the output use.
Do not silence the error by weakening the member types. Doing so removes the safety the annotation was meant to give you.
What `in` does not change
The modifier does not change runtime behavior, because it is erased during compilation. It does not make an unsafe type safe. It records your intent, and the compiler verifies the claim.
Without an annotation, TypeScript measures variance on its own by inspecting how T is used. For Consumer the inferred result is the same as the annotated one. Adding in changes the result only if your declaration contradicts the structure. The benefits come from the annotation's other effects, covered in a later chapter: it documents the design, it can speed up checking of large or recursive generic types, and it can resolve cases where inference produces a poor answer.
Annotations are allowed only on type parameters of interfaces, classes, and type aliases for object, function, constructor and mapped types. They are not valid on a function's own type parameters, and the compiler reports an error if you try.
Common mistakes
- Putting
inon a parameter that is also returned. A getter or a returned property makes the type invariant. Usein out, or split the type into a reader and a writer. - Forgetting the double flip. A callback inside a parameter puts
Tback in an output position. Count the flips before choosingin. - Assuming the compiler checks method parameters. Under bivariance,
inandouton method-only parameters are barely checked. Use function-typed properties for enforcement. - Expecting
into affect values at runtime. It affects only assignability between instantiations at compile time. - Compiling without
strictFunctionTypes. Without it, function-typed properties are bivariant too, and the check oninloses its force.
Exercise
You write interface Logger<in T> { log: (value: T) => void; last: () => T | undefined; }. The compiler reports an error about a variance annotation. Which member causes it, why, and what are two ways to fix it?
Show answer
The member last causes it, because T appears in its return type, an output position. That contradicts in, which says T is only consumed. Fix 1: change the annotation to in out T, since Logger now both reads and writes T and is invariant. Fix 2: remove last, or move it to a separate reader interface, so that T is only consumed and in holds.
Exercise
Given type Comparer<in T> = (a: T, b: T) => number; and declare const byName: Comparer<Animal>;, which assignment compiles: const x: Comparer<Dog> = byName; or declare const byBark: Comparer<Dog>; const y: Comparer<Animal> = byBark;? Explain in one sentence.
Show answer
Only the first compiles. A comparer that handles any Animal can compare Dogs, but a comparer written for Dogs might be handed a non-Dog Animal, so the contravariant direction runs from Comparer<Animal> to Comparer<Dog>.