Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of bivarianceHack in TypeScript types?

While reading through the TypeScript types for React, I saw a few usages of this pattern involving a bivarianceHack() function declaration:

@types/react/index.d.ts

type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void }["bivarianceHack"];

Searching didn't lead me to any documentation on why this particular pattern was used, although I've found other instances of this pattern in use so it seems it's not a React-specific pattern.

Why is this pattern being used rather than (event: E) => void?

like image 498
zzzzBov Avatar asked Oct 05 '18 14:10

zzzzBov


1 Answers

This has to do with function compatibility under the strictfunctionTypes option. Under this option if the argument is of a derived type you can't pass it to a function that will pass in a base class argument. For example:

class Animal { private x:undefined }
class Dog extends Animal { private d: undefined }

type EventHandler<E extends Animal> = (event: E) => void

let o: EventHandler<Animal> = (o: Dog) => { } // fails under strictFunctionTypes

There is however a caveat to strict function type, stated in the PR

The stricter checking applies to all function types, except those originating in method or constructor declarations. Methods are excluded specifically to ensure generic classes and interfaces (such as Array<T>) continue to mostly relate covariantly. The impact of strictly checking methods would be a much bigger breaking change as a large number of generic types would become invariant (even so, we may continue to explore this stricter mode).

Emphasis added

So the role of the hack is to allow the bivariant behavior of EventHandler even under strictFunctionTypes. Since the signature of the event handler will have its source in a method declaration it will not be subject to the stricter function checks.

type BivariantEventHandler<E extends Animal> = { bivarianceHack(event: E): void }["bivarianceHack"];
let o2: BivariantEventHandler<Animal> = (o: Dog) => { } // still ok  under strictFunctionTypes 

Playground link

like image 135
Titian Cernicova-Dragomir Avatar answered Oct 23 '22 08:10

Titian Cernicova-Dragomir