Sub topic 6
Why method declarations stay bivariant
This chapter assumes you know the Animal/Dog pair from earlier in the tutorial. It also assumes you know how covariance, contravariance and invariance work, and that you compile with "strict": true. Here you will see that strictFunctionTypes does not check every function parameter contravariantly. Members declared with method syntax are still checked bivariantly, and that exception explains why Array<Dog> is assignable to Array<Animal>.
The two checks side by side
With strictFunctionTypes on, the compiler compares function parameters contravariantly. A function that accepts Animal can stand in for one that accepts Dog, but not the other way around.
The compiler skips that rule for parameters of members declared with method syntax. For those it uses the older bivariant check, which accepts the assignment when the parameter types are assignable in either direction.
Two declarations that look nearly the same therefore behave differently:
interface FnProp {
handle: (a: Animal) => void; // property holding a function type: strict
}
interface Meth {
handle(a: Animal): void; // method declaration: bivariant
}The compiler decides by how the member is written, not by what it means. The rule covers method signatures in interfaces and type literals, method shorthand in object literals, and class methods. Constructor types and construct signatures are exempt as well.
What bivariance accepts
Bivariant means the compiler accepts a parameter pair if the source parameter type is assignable to the target's, or the target's to the source's. With Dog and Animal both directions are related, so both assignments compile:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
class Cat extends Animal {
meow() {
return "meow";
}
}
interface Meth {
handle(a: Animal): void;
}
const dogHandler = {
handle(d: Dog): void {
console.log(d.bark());
},
};
// Allowed: Dog is narrower than Animal, and methods accept that.
const animalHandler: Meth = dogHandler;
// Compiles, because Cat is an Animal.
// At runtime this throws: d.bark is not a function.
animalHandler.handle(new Cat());The assignment const animalHandler: Meth = dogHandler is unsound. Meth promises to accept any Animal, but the object behind it only copes with a Dog. Under contravariance this assignment would be rejected, because (d: Dog) => void is not a (a: Animal) => void.
Bivariance is still not "anything goes". If neither parameter type is assignable to the other, the compiler reports an error:
interface Parser {
parse(input: string): void;
}
const numberParser = {
parse(input: number): void {
console.log(input.toFixed(2));
},
};
// Error: string and number are unrelated, so neither direction works.
// const p: Parser = numberParser;The unsoundness is limited to parameter types that are related by subtyping. It lets through the narrowing of a parameter, such as Animal to Dog, and not arbitrary mismatches.
Why the exception exists
Before strictFunctionTypes arrived in TypeScript 2.6, all function parameters were bivariant. Making them strict everywhere would have broken a large amount of existing code, and the TypeScript team chose to exempt methods on purpose. The reason is the built-in generic types.
Consider a simplified Array:
interface MyArray<T> {
push(...items: T[]): number;
indexOf(item: T): number;
readonly length: number;
}T appears in the parameters of push and indexOf. If those parameters were checked contravariantly, T would be used both as an input and, through the index signature and the other members, as an output. That makes MyArray<T> invariant, and Dog[] would no longer be assignable to Animal[]. Passing a string[] to a function that accepts (string | number)[] would then be an error. Code like that is everywhere, and most people expect it to work.
Method bivariance keeps these generic containers covariant in practice. You can see the effect by writing the same shape twice, once with methods and once with function-typed properties:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface MethodBox<T> {
get(): T;
add(value: T): void;
}
interface PropBox<T> {
get: () => T;
add: (value: T) => void;
}
declare const dogMethodBox: MethodBox<Dog>;
const animalMethodBox: MethodBox<Animal> = dogMethodBox; // OK: method parameters are bivariant
declare const dogPropBox: PropBox<Dog>;
// const animalPropBox: PropBox<Animal> = dogPropBox;
// Error: add's parameter is checked contravariantly, so PropBox is invariant in TMethodBox<T> behaves covariantly because its only strict position is the return type of get. PropBox<T> behaves invariantly because get demands covariance and add demands contravariance.
Choosing between method and property syntax
The same logic gives you a tool. Declaring a member with method syntax or with a function-typed property selects the check the compiler applies to its parameters.
| Declaration | Example | Parameter check under `strictFunctionTypes` |
|---|---|---|
| Method signature | `handle(a: Animal): void` | Bivariant |
| Function-typed property | `handle: (a: Animal) => void` | Contravariant |
| Method shorthand in an object literal | `{ handle(a: Animal) {} }` | Bivariant |
| Arrow function property | `{ handle: (a: Animal) => {} }` | Contravariant |
| Function type alias | `type H = (a: Animal) => void` | Contravariant |
Use method syntax when the type is a collection or other container, and subtype assignments like Box<Dog> to Box<Animal> should keep working. Use a function-typed property for callbacks and event handlers, where a wrong-parameter assignment would crash at runtime. A property also documents that the member is a replaceable value, not a fixed part of the type's behaviour.
A few details are worth knowing:
- Overloaded methods are compared per signature with the same bivariant rule.
- The check follows the declaration site. If you write
type M = Meth["handle"], the extracted type still remembers that it came from a method, so it keeps the bivariant check. - If
strictFunctionTypesis off, every function parameter is bivariant. Turning on"strict": trueenables it automatically.
Consequences for variance annotations
The in and out modifiers state variance explicitly. The compiler verifies them with its normal assignability rules, so method bivariance applies there too. A type parameter used only in method parameters is not necessarily treated as contravariant. Later chapters on annotations show how to use this knowledge when deciding whether to write them.
For now, remember the rule of thumb that the position of a type parameter determines its variance, with one exception. A type parameter used as the parameter of a method is effectively bivariant, which in practice means the type is treated as covariant in it.
Common mistakes
- Assuming that
strictFunctionTypesprotects every function parameter. It does not protect method-syntax members. - Converting a method to a property to "clean up" an interface. This can make a generic type invariant and break assignments that used to compile.
- Expecting unrelated parameter types to pass. Bivariance requires the types to be related by subtyping in one direction.
- Treating an unsound-but-allowed assignment as proof that the code is safe. The compiler accepted it for compatibility, not because it is correct.
Exercise
Given interface A { run(x: Dog): void } and interface B { run: (x: Dog) => void }, and a value declare const a: { run(x: Animal): void }, which of const x: A = a and const y: B = a compile under strict, and what changes if the value is instead declare const d: { run(x: Dog): void } assigned to { run(x: Animal): void } and to { run: (x: Animal) => void }?
Show answer
Both const x: A = a and const y: B = a compile, because a function accepting Animal can safely stand in for one accepting Dog (contravariance, which is allowed in both cases). For the second part, assigning d to { run(x: Animal): void } compiles because method parameters are bivariant, but assigning it to { run: (x: Animal) => void } is an error, because the property is checked contravariantly and Animal is not assignable to Dog.