Sub topic 12
What Happens When an Annotation Contradicts the Type
This chapter assumes you know generics, interfaces, and structural assignability. It also assumes you have "strict": true (or at least "strictFunctionTypes": true) turned on. You have seen that out, in, and in out state a type parameter's variance. Here you will see what the compiler does when the statement is wrong, and which wrong statements it can't catch.
The annotation is a claim the compiler verifies
Without an annotation, TypeScript measures variance from the structure of the type. With an annotation, you make a claim about that structure, and the compiler checks the claim at the declaration.
The check works like this:
- The compiler instantiates your type twice, using two marker types. One marker is a subtype of the other, so they stand in for
DogandAnimal. - It tests assignability in the direction your annotation promises.
- If the test fails, it reports an error on the type parameter.
The promised directions are:
| Annotation | What the compiler requires |
|---|---|
| `out T` | `X<sub>` is assignable to `X<super>` |
| `in T` | `X<super>` is assignable to `X<sub>` |
| `in out T` | Nothing is checked, because invariance is always safe to claim |
The shared setup for the examples below is the same pair of classes as before:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}Claiming `out` for a type that consumes
Here is a type that takes a T as input but is marked out:
// 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
}The compiler checks whether Writer<sub> is assignable to Writer<super>. The property write would then need (value: sub) => void to be assignable to (value: super) => void. Under strictFunctionTypes, parameters are checked contravariantly, so that fails.
The error is reported on the declaration of T, not on any line that uses Writer. It reads roughly like this:
error TS2636: Type 'Writer<sub-T>' is not assignable to type 'Writer<super-T>' as implied by variance annotation.
Types of property 'write' are incompatible.
...sub-T and super-T are the compiler's marker types. The useful part is the "Types of property" line below the headline, because it names the member that contradicts your annotation.
This error always points at the declaration. No Writer<Dog> or Writer<Animal> needs to exist anywhere in your program for it to appear.
Claiming `in` for a type that produces
The reverse mistake gives the mirror-image error:
interface Source<in T> {
get(): T; // Error: T is used in an output position, which contradicts in
}For in T, the compiler needs Source<super> to be assignable to Source<sub>. That requires get(): super to be assignable to get(): sub, which fails. The headline says that Source<super-T> is not assignable to Source<sub-T>. The two marker names appear in the opposite order from the out case, and that order tells you which direction you promised.
Ways to fix it
When you see TS2636, you have three honest options:
- Correct the annotation. If
Tis only consumed, usein. If it is only produced, useout. - Use
in out. IfTis both read and written, invariance is what the type really has. - Change the structure. If you meant
out, remove the input use ofT, for example by replacing awrite(value: T)member with something that doesn't takeT.
Removing the annotation is also valid, because the compiler will measure the variance itself. But that discards the documentation and the guard rail, which is why you added it in the first place.
`in out` can't be contradicted
Because invariance is the most restrictive claim, no structure violates it. This compiles however T is used:
interface Box<in out T> {
get(): T;
set(value: T): void;
}
interface OnlyReads<in out T> {
get(): T;
}OnlyReads is checked by no one, even though out would be accurate. The compiler won't tell you the annotation is too strict. It just rejects assignments such as OnlyReads<Dog> to OnlyReads<Animal>, which are safe. If you find yourself writing in out on a read-only type, you are giving up flexibility for nothing.
Wrong annotations that still compile
The check is only as precise as TypeScript's assignability rules. Two of those rules are deliberately loose, so a wrong claim can slip through.
Method parameters are bivariant. This was covered earlier in the chapter on method bivariance. A method declaration that takes T does not contradict out T:
interface MethodWriter<out T> {
write(value: T): void; // compiles: method parameters stay bivariant
}
declare const dogWriter: MethodWriter<Dog>;
const animalWriter: MethodWriter<Animal> = dogWriter; // allowed, but unsafeanimalWriter.write(new Animal()) type-checks and then hands a plain Animal to code that expects a Dog.
Mutable properties count as reads. A property of type T is treated as covariant, so it doesn't contradict out T either:
interface Cell<out T> {
value: T; // compiles: property types are compared as reads
}
const dogCell: Cell<Dog> = { value: new Dog() };
const animalCell: Cell<Animal> = dogCell; // allowed
animalCell.value = new Animal(); // compiles
// dogCell.value.bark(); // would now fail at runtime: the value is not a DogThis is the same unsoundness that arrays have. To make the annotation honest, mark the property readonly:
interface SafeCell<out T> {
readonly value: T;
}Now animalCell.value = ... is an error through any SafeCell.
What the check does not do
- It doesn't change how the type is measured when the annotation is correct. It only adds an up-front verification and lets the compiler skip a structural comparison.
- It doesn't produce errors at use sites. Assigning
Producer<Animal>toProducer<Dog>fails for the usual assignability reason, with or without an annotation. - It doesn't override the structure. You can't make a consumer assignable "upwards" by annotating it
out. You can only get an error, or, through the gaps above, an unsafe success.
A debugging routine
If the annotation is already correct and an assignment still fails at a use site, the problem is the assignment. Check the direction against the table at the start of this chapter before touching the annotation.
Exercise
Why does interface Logger<out T> { log(value: T): void } compile, while interface Logger<out T> { log: (value: T) => void } produces TS2636 under strict?
Show answer
Under strictFunctionTypes, parameters of function-typed properties are checked contravariantly, so T in an input position contradicts out. Method declarations keep the older bivariant parameter check, so the compiler finds no contradiction, even though the claim is unsound for a consumer.
Exercise
A teammate writes interface Reader<in T> { read(): T } and gets an error whose headline mentions Reader<super-T> and Reader<sub-T>. What are the two correct fixes?
Show answer
T appears only as a return type, so the type is covariant and the annotation should be out T. Alternatively, remove the annotation and let the compiler infer the variance. Using in out T also compiles, but it needlessly forbids safe assignments such as Reader<Dog> to Reader<Animal>.
Exercise
Why can interface Cell<out T> { value: T } compile even though assigning through a Cell<Animal> that really holds a Dog cell is unsafe, and how do you make the annotation trustworthy?
Show answer
The variance check treats a property of type T as a read, so the type looks covariant and the write that makes it unsafe is not checked. Making the property readonly removes the write, so the out claim becomes accurate.