Minh Nghĩa
Minh Nghĩa

Reputation: 1059

TypeScript narrow too much for a generic function

MWE, Playground:

function bar<T extends string | number>(a: T, b: T): T {
  if (typeof a !== typeof b) throw 'what';
  return a + b;
}

const a = bar(1, 2)
const b = bar('1', '2')

I want to create a overload function that takes either 2 strings or 2 numbers. I know about the overload syntax of TS, but with that I have to check typeof repeatedly.

Now I want to use generic instead. However, TS reports bar() in the line bar(1, 2) is of the type that only takes 1 | 2 and only returns 1 | 2. Same for the second call, this time "1" | "2".

Why does TS "over" narrow in this case? What can I do to fix this?

Upvotes: 1

Views: 17

Answers (0)

Related Questions