What is the purpose of bivarianceHack in TypeScript types?

TypescriptTypes

Typescript Problem Overview


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?

Typescript Solutions


Solution 1 - Typescript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzzzzBovView Question on Stackoverflow
Solution 1 - TypescriptTitian Cernicova-DragomirView Answer on Stackoverflow