hegel
hegel copied to clipboard
Unsound type inference with arithmetic operators
Consider the following function:
let f = (a, b) => a + b
The inferred type is
<T: bigint | number | string>(T, T) => T
This might seem correct, but actually is unsound:
let f = (a, b) => a + b
const a: number | bigint = 1;
const b: number | bigint = 1n;
const x = f(a, b); // TypeError thrown
This applies to all arithmetic operators.
it's not inference problem inference is 100% legit
let f = <T: string | number>(a: T, b: T) => a + b
const a: string | number = 1
const b: string | number = 'cotne'
void f(a, b) // should error and does not
but generics should not allow usage of unions
because while function accepts both string and number it does not accepts both of them at same time if it did then generics are not needed
but generics should not allow usage of unions
They should allow it, but that's not what should be inferred in this case.