Search code examples
typescriptgenericstype-narrowing

Typescript: function with n parameters of union type T, why does inferring one param's type not infer all, when callers must match types?


Given this function signature: function foo<T extends X | Y>(bar: T, baz: T) {}
Callers cannot mix X and Y. The compiler enforces that bar and baz are either both X, or both Y

However, a type check on bar narrows its type, but not that of baz. Proof: ts playground

Can this symmetry outside the method body be continued into the method body somehow, so that 1 type check narrows all parameters?


Solution

  • Your assumption is wrong; a legal call to compare would be

    compare<string | number>(10, "");
    

    Thus it is not valid to narrow one parameter based on the other's type