I know this question is already been asked here on StackOverflow and GitHub. In this question, I want to extend their conversation. As typescript core team member RyanCavanaugh said:
Everything described so far is the intended behavior. Not inferring union types from disparate candidates is 100% intentional; this doesn’t yield expected results in a huge majority of cases even though it can be theoretically justified.
But using a trick I managed to make both types a and b as same. But still typescript is not able to figure out both a and b would be the same.
type Addable = string | number
type BeSame<T>= T extends number ? number : string
function addMe<T extends Addable,U extends BeSame<T>>(a: T,b: U) {
return a+b;
}
-Operator '+' cannot be applied to types 'T' and 'U'
Expected Behaviour:
Since I’m telling typescript both a and b type would be the same it should allow me to use +
operator on a and b.
addMe("helo", 2); // error cuz a and b are not same
addMe(4,5); // fine a and b are same
addMe("hello", "hello"); // also fine
1