hegel icon indicating copy to clipboard operation
hegel copied to clipboard

Unsound type inference with arithmetic operators

Open vkurchatkin opened this issue 4 years ago • 2 comments

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.

vkurchatkin avatar May 21 '20 21:05 vkurchatkin

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

try

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

thecotne avatar May 21 '20 22:05 thecotne

but generics should not allow usage of unions

They should allow it, but that's not what should be inferred in this case.

vkurchatkin avatar May 21 '20 22:05 vkurchatkin