Consider
const pairer = <T,>(a: T, b:T) => ({a, b})
const mypair = pairer(3n, true)
This is an error in TypeScript 4.9, namely
Argument of type boolean is not assignable to parameter of type bigint
So clearly TS has inferred T to be bigint in the call, making the call invalid. But there is a perfectly good type for T that makes the call legal, namely bigint | boolean
:
const myotherpair = pairer<bigint | boolean>(3n, true)
compiles and runs fine.
Why doesn't TypeScript infer the type that makes the code it is processing valid? Is there a concise writeup of the inference of a generic parameter from an actual call with enough detail to understand why it chose bigint
in the mypair
call? (The TypeScript handbook page on generics doesn't cover cases with two uses of the parameter.) And perhaps most importantly, is there a way for me to define my generic so that the unadorned call mypair(x,y) will infer the type (typeof x) | (typeof y)
?