Sub topic 14
Where Variance Annotations Are Allowed and What They Do Not Change
This chapter covers the limits of in, out, and in out. You will learn which declarations accept them, which ones reject them, and which parts of type checking they leave alone. It assumes you have read the earlier chapters on covariance, contravariance, invariance, strictFunctionTypes, and method bivariance. It also assumes you know the Animal and Dog classes used throughout this tutorial.
Where annotations are allowed
Variance annotations (TypeScript 4.7 and later) go directly in front of a type parameter name in a declaration. They are accepted on three kinds of declaration:
| Declaration | Allowed | Notes |
|---|---|---|
| `interface` | Yes | The most common place. |
| `class` | Yes | Checked against the class's instance type. |
| `type` alias | Only for some shapes | The alias must name an object, function, constructor, or mapped type. |
| Function or method type parameters | No | There is no generic type to compare, so variance has no meaning. |
| Type parameters of a call signature inside an interface | No | Same reason. |
The following code shows the accepted forms.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Producer<out T> {
get(): T;
}
class Counter<in out T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
first(): T | undefined {
return this.items[0];
}
}
type Handler<in T> = (value: T) => void;
type Factory<out T> = new () => T;
type Config<out T> = { readonly value: T };
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer;
declare const animalHandler: Handler<Animal>;
const dogHandler: Handler<Dog> = animalHandler;
declare const dogFactory: Factory<Dog>;
const animalFactory: Factory<Animal> = dogFactory;
declare const dogConfig: Config<Dog>;
const animalConfig: Config<Animal> = dogConfig;
console.log(animalProducer, dogHandler, animalFactory, animalConfig, new Counter<Dog>());Variance only describes how two instantiations of the same generic type relate. A generic function has no instantiations to compare, so the compiler rejects annotations there.
// function identity<out T>(value: T): T { return value; }
// Error: 'out' modifier can only appear on a type parameter of a class, interface or type alias
// interface Mapper {
// map<in T>(value: T): T;
// }
// Error: the same message, because the parameter belongs to a method signatureType aliases need a suitable shape
A type alias can only carry an annotation when its right-hand side is an object, function, constructor, or mapped type. A union, intersection, conditional type, or alias that only renames another type is rejected.
// type MaybeValue<out T> = T | undefined;
// Error: variance annotations are only supported in type aliases
// for object, function, constructor, and mapped types
// type Unwrap<out T> = T extends Promise<infer U> ? U : T;
// Error: same message, because the right side is a conditional typeThe reason is that the compiler measures variance by comparing instantiations of the alias structurally. For unions and conditional types, no stable parameter-by-parameter comparison exists, so the compiler declines to accept a claim about it. If you need an annotation, wrap the shape in an object type or an interface.
interface Maybe<out T> {
readonly value: T | undefined;
}
declare const maybeDog: Maybe<Dog>;
const maybeAnimal: Maybe<Animal> = maybeDog;
console.log(maybeAnimal);Syntax rules
The modifiers are part of the type parameter, so they sit before its name and before extends or a default.
interface Source<out T extends Animal = Animal> {
next(): T;
}
interface Pipe<in I, out O> {
run(input: I): O;
}
interface Slot<in out T> {
get(): T;
set(value: T): void;
}Three rules apply:
- Each type parameter has its own annotation. Annotating
Isays nothing aboutO. in outmust be written in that order.out inis a syntax error.- You cannot repeat a modifier.
in in Tandout out Tare errors.
A parameter with no modifier keeps the inferred variance, as in earlier chapters. Mixing annotated and unannotated parameters in one declaration is fine.
What annotations do not change
An annotation is a statement about a type. It is a compile-time check plus a hint to the compiler. It does not change how the type behaves. The sections below cover the points that surprise people most.
Nothing exists at runtime
Annotations are erased during compilation. The emitted JavaScript for class Counter<in out T> is identical to the output for class Counter<T>. They add no checks, no wrappers, and no cost when the program runs.
Method bivariance still applies
The compiler checks an annotation against the declaration's structure, and that check follows the usual rules. Method declarations compare their parameters bivariantly, so a method can use an out parameter in an input position without an error.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Sink<out T> {
push(value: T): void; // method syntax: accepted despite the input position
}
const dogs: Dog[] = [];
const dogSink: Sink<Dog> = {
push(value: Dog) {
dogs.push(value);
console.log(value.bark());
},
};
const animalSink: Sink<Animal> = dogSink; // compiles
animalSink.push(new Animal()); // compiles, then fails at runtime: no bark()If you write the same member as a property, push: (value: T) => void, the compiler reports an error for out T. The annotation did not make the method version safe. It only recorded a claim that the compiler could not disprove.
Arrays stay covariant
Annotations cannot change the built-in rule for Array<T>. A mutable array of Dog is still assignable to Animal[]. If you wrap an array in your own type and want stricter behavior, annotate your type with in out. The next section shows how.
Other checks are untouched
- Inference: An annotation does not change how
Tis inferred at a call site. It affects only comparisons between two instantiations of the annotated type. - Structural comparison between different types: If you assign an object literal or a value of an unrelated type to
Producer<Animal>, the compiler still compares structure. The annotation applies only when both sides are instantiations of the same generic declaration. - Constraints and defaults:
extendsand=clauses work independently of variance. strictFunctionTypes: The flag still decides whether function-typed properties are checked contravariantly. An annotation neither enables nor disables it.
Annotations can tighten but not loosen
The compiler allows an annotation that is stricter than the measured variance, and rejects one that is looser. Looser would mean claiming out for a parameter that is written to. Stricter means claiming in out for a parameter that is only read.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Token<in out T> {
readonly value: T; // only read, so structurally covariant
}
declare const dogToken: Token<Dog>;
// const animalToken: Token<Animal> = dogToken;
// Error: Token is declared invariant in T
console.log(dogToken);Tightening is useful for brand-like or identifier types where you want Id<User> and Id<Admin> kept apart even when User and Admin are related by subtyping. The stricter annotation also stops later edits to the interface from silently widening what is assignable.
Practical checklist
Use this list when an annotation is rejected or does not behave as you expected.
- Confirm the parameter is on an interface, class, or type alias. Move it off functions and methods.
- If it is an alias, confirm the right side is an object, function, constructor, or mapped type. Otherwise switch to an interface.
- Check the order
in outand make sure no modifier repeats. - If a mismatch error appears, look for the parameter in an input or output position that contradicts the modifier. Function-typed properties count as inputs.
- If an annotation is accepted but the type is still unsound, look for method syntax and replace it with a function-typed property.
- Remember that an annotation describes a relationship between instantiations. It does not change runtime behavior or inference.
Exercise
Which of these declarations would the compiler reject, and why? (a) interface A<out T> { get(): T } (b) type B<out T> = T | null (c) function c<in T>(x: T): void {} (d) class D<in out T> { value!: T }
Show answer
(b) and (c) are rejected. (b) is a type alias whose right side is a union, and annotations on aliases are limited to object, function, constructor, and mapped types. (c) puts a variance modifier on a function's type parameter, and annotations are only allowed on classes, interfaces, and type aliases. (a) is a valid covariant interface. (d) is valid, because in out states invariance and a mutable property is invariant anyway.
Exercise
interface Store<out T> { put(value: T): void } compiles without errors. Does that make Store<Dog> safe to use as a Store<Animal>? How would you change the declaration so the compiler checks the claim?
Show answer
No. put is a method declaration, so its parameter is compared bivariantly and the compiler does not flag the input position. Store<Dog> can then be assigned to Store<Animal> and receive an Animal at runtime. Write the member as a function-typed property, put: (value: T) => void. With strictFunctionTypes on, the compiler then reports that T is used in an input position, which contradicts out. The correct annotation for a type that only receives values is in.