Issue
Here is the code.
type Combinable = string | number;
function add(n: Combinable, b: Combinable) {
if (typeof n === 'string'&& typeof b ==='string') {
return n.toString() + b.toString();
} else if (typeof n === 'string'&& typeof b ==='number') {
return n.toString() + b.toString();
} else if (typeof n === 'number'&& typeof b ==='string') {
return n.toString() + b.toString();
} else {
// here raises error
// Operator '+' cannot be applied to types 'Combinable' and 'Combinable'.ts(2365)
return n + b;
}
}
// But it works fine when I change "and" operator to "or" operator.
function add(n: Combinable, b: Combinable) {
if (typeof n === 'string' || typeof b ==='string') {
return n.toString() + b.toString();
} else {
return n + b;
}
}
As you can see, I got the error on the last line n + m
.
I thought it should work if I cover all cases, but the error still remains.
What am I missing here?
Solution
The problem is that the type comparisons you're doing in the if
statements with &&
can't narrow down the type of any individual parameter.
After doing
if (typeof n === 'string' && typeof b ==='string') {
TS isn't smart enough to recognize that this means that either n
or b
is not a string: both n
and b
are still typed as Combinable
.
Using ||
, on the other hand, makes it parseable, because it's absolutely certain that both n
and b
are not strings after that branch ends.
One way to fix it would be to nest the if/elses:
function add(n: Combinable, b: Combinable) {
if (typeof n === 'string') {
if (typeof b === 'string') {
return n.toString() + b.toString();
} else if (typeof b === 'number') {
return n.toString() + b.toString();
}
} else if (typeof n === 'number') {
if (typeof b === 'string') {
return n.toString() + b.toString();
} else {
return n + b;
}
}
}
(can also use just else
instead of else if(cond)
, since there are no other alternatives)
Answered By - CertainPerformance
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.