Skip to content
jshacks.dev
TypeScript

Function Type Compatibility and Bivariance

How TypeScript decides whether one function type fits another, why method parameters are bivariant, and what strictFunctionTypes changes, with exact errors.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.

When you assign one function to a variable of another function type, TypeScript has to decide whether the assignment is safe. The rules cover the number of parameters, the types of the parameters, and the return type, and one of them, how parameter types are compared, has a history that explains a surprising amount of everyday behaviour. A function that takes a Dog is accepted where a function that takes an Animal is expected, as long as it is written one way, and rejected when it is written another way. This post explains the rules, defines variance in plain terms, shows the exact errors, and explains the strictFunctionTypes option and the method syntax exception. It describes TypeScript 6.x with strict on, and the same rules apply in the native compiler preview that TypeScript 7 is built on. The reference is the handbook section on type compatibility and the strictFunctionTypes entry in the tsconfig reference.

The types used below

Every example uses the same two types, one a subtype of the other.

types.tsTypeScript
interface Animal {
  name: string;
}

interface Dog extends Animal {
  bark: () => void;
}

A Dog has everything an Animal has and more, so a Dog can be used wherever an Animal is expected. That is the subtype relationship, and it is the starting point for variance.

What variance means

Variance describes how a relationship between two types carries over to types built from them. Covariant means the relationship keeps its direction: if Dog is a subtype of Animal, then Dog[] is a subtype of Animal[]. Contravariant means the direction flips: a consumer of Animal can stand in for a consumer of Dog, because anything that handles every animal can handle a dog. Bivariant means either direction is accepted. Invariant means neither is.

For functions, the return type is a producer, so it is covariant. The parameter type is a consumer, so, if you want a sound type system, it should be contravariant. A function that accepts any Animal is a safe replacement for one that is only ever called with a Dog. The reverse is not safe, because a function that expects a Dog may call bark, and an arbitrary Animal has no such method.

Return types are covariant

A function that returns a Dog can be used where a function returning an Animal is expected.

returns.tsTypeScript
declare const makeDog: () => Dog;
declare const makeAnimal: () => Animal;

const a: () => Animal = makeDog;
const b: () => Dog = makeAnimal;
Text
returns.ts(5,7): error TS2322: Type '() => Animal' is not assignable to type '() => Dog'.
  Property 'bark' is missing in type 'Animal' but required in type 'Dog'.

The first assignment passes, since every Dog is an Animal. The second fails, because a caller who expects a Dog would call bark on a result that might not have it. This is the rule most people expect, and it is the same in every strictness setting.

Parameter types are contravariant under strictFunctionTypes

With the strictFunctionTypes option on, which is part of strict, parameters of function types are compared contravariantly.

params.tsTypeScript
type AnimalHandler = (a: Animal) => void;
type DogHandler = (d: Dog) => void;

declare const handleAnimal: AnimalHandler;
declare const handleDog: DogHandler;

const x: DogHandler = handleAnimal;
const y: AnimalHandler = handleDog;
Text
params.ts(8,7): error TS2322: Type 'DogHandler' is not assignable to type 'AnimalHandler'.
  Types of parameters 'd' and 'a' are incompatible.
    Property 'bark' is missing in type 'Animal' but required in type 'Dog'.

Assigning the animal handler to the dog slot is fine, because the handler accepts more than it will be given. Assigning the dog handler to the animal slot is rejected, because the caller may pass any animal, and the handler would then read a bark that is not there. The message points at the parameter pair and names the missing property, and that is the shape of every parameter error you will see.

Bivariance without strictFunctionTypes

Before strictFunctionTypes was added in TypeScript 2.6, the compiler compared parameters bivariantly: an assignment was accepted if the parameter types were related in either direction. The second assignment above would have compiled. Turning the option off restores that behaviour, and projects that set strict: false and never enable the individual flag still have it.

The reason for the old rule is practical. JavaScript code passes callbacks everywhere, and many of them are written for a narrower type than the API promises. Consider the DOM, where an event handler for a specific element is often registered through an API typed with a general event. Strict contravariance rejects many such patterns. The language chose to allow them first and tighten later, with an opt-in flag so existing code kept compiling. Strict mode is now the normal setting for new projects, so the contravariant behaviour is what you should expect.

The method syntax exception

The tightening has one deliberate exception. Parameters declared with method syntax stay bivariant, even under strictFunctionTypes. The handbook documents this: the strict check applies to function type properties and not to methods or constructors.

methods.tsTypeScript
interface Strict {
  handle: (a: Animal) => void;
}

interface Loose {
  handle(a: Animal): void;
}

const dogOnly = (d: Dog): void => {
  d.bark();
};

const s: Strict = { handle: dogOnly };
const l: Loose = { handle: dogOnly };
Text
methods.ts(13,21): error TS2322: Type '(d: Dog) => void' is not assignable to type '(a: Animal) => void'.
  Types of parameters 'd' and 'a' are incompatible.
    Property 'bark' is missing in type 'Animal' but required in type 'Dog'.

The property form is rejected and the method form compiles, even though the two declare the same thing. The reason is compatibility with built-in types. If methods were strict, a type such as Array<Dog> would no longer be assignable to Array<Animal>, because methods like push take the element type as a parameter, and a method with a Dog parameter would not accept an Animal. That would break a very common and mostly harmless pattern. Keeping methods bivariant preserves covariant arrays at the cost of a hole in soundness: you can push a plain animal into what is really an array of dogs.

This means the choice between handle: (a: Animal) => void and handle(a: Animal): void in an interface is a choice about strictness. When you want the compiler to enforce that handlers accept everything they might be given, use the property form. When you want the looser behaviour, for example to describe a class whose methods you will extend, use the method form.

Parameter count

The number of parameters follows a simpler rule. A function with fewer parameters can be used where one with more is expected, because the extra arguments are ignored. The reverse is an error.

count.tsTypeScript
type TwoArgs = (a: number, b: number) => void;
type OneArg = (a: number) => void;

declare const takesTwo: TwoArgs;
declare const takesOne: OneArg;

const p: TwoArgs = takesOne;
const q: OneArg = takesTwo;
Text
count.ts(8,7): error TS2322: Type 'TwoArgs' is not assignable to type 'OneArg'.
  Target signature provides too few arguments. Expected 2 or more, but got 1.

This is why array.map(x => x * 2) compiles even though map calls its callback with three arguments: a callback that declares only the first one is compatible. Optional and rest parameters are compared by the same idea, with an optional parameter treated as one the caller may omit.

Return type void

A function type that returns void accepts a function that returns anything. The result is simply not used by the caller.

void.tsTypeScript
type Callback = () => void;

const cb: Callback = () => 42;
const n: number = cb();
Text
void.ts(4,7): error TS2322: Type 'void' is not assignable to type 'number'.

The assignment on line 3 is allowed, and the call on line 4 shows the type of the result is still void. This rule is what lets you pass list.push or an arrow function with an expression body to something that wants a callback. The literal form is different: an inline function expression written with an explicit : void return annotation may not return a value.

Practical guidance

Keep strict on, so strictFunctionTypes is on, and let the compiler catch callbacks written for a narrower type than they will receive. When the compiler rejects a handler, the usual fix is to widen the handler's parameter and narrow inside it with a type guard, not to loosen the declaration.

When designing an interface, prefer the property form for callbacks that the implementer supplies, and the method form only when you need the covariance of containers or are describing something the host defines. If you write a generic container, think about whether the type parameter appears in parameter positions, return positions, or both, since that decides whether the container is covariant, contravariant or invariant in it. TypeScript lets you state this with the in and out variance annotations on type parameters, added in 4.7, which also let the compiler skip a structural comparison.

Common mistakes

The first is assuming that a function taking Dog can be used where one taking Animal is expected, because Dog is the more specific type. Under strict checking it cannot, and the direction is the opposite of what intuition suggests. The second is changing handle: (a: Animal) => void to a method to silence an error, which hides a real unsoundness. The third is forgetting that the loose behaviour still applies to methods, so a green build does not prove the handler is safe. The fourth is reading "fewer parameters is fine" as "extra parameters is fine"; only the first is allowed.

When this does not apply

If strict is off, parameters are bivariant everywhere and most of the contravariance errors above do not appear. In that case the compiler is not protecting you from the handler mismatch, so add your own checks, or turn on strictFunctionTypes alone and fix what it reports. The rules also only concern the declared types. At run time JavaScript does not check any of this, so a mismatched callback fails only when it is called.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.