48
loading...
This website collects cookies to deliver better user experience
const
." The issue had been open since 2016 and it was closed because it was covered by a pull request addressing control flow analysis of aliased conditional expressions and discriminants.Lack of type narrowing with consts made me repeat code, or avoid helpfully namef consts, too many times
'2'
as it would 2
.function add(...thingsToAdd: (string | number)[]): number {
let total = 0;
for (const thingToAdd of thingsToAdd) {
if (typeof thingToAdd === 'string') {
total += Number(thingToAdd);
} else {
total += thingToAdd;
}
}
return total;
}
console.log(add(1, '7', '3', 9))
typeof thingToAdd === 'string'
serves two purposes:string | number
to string
string
can be coerced into a number
and added to the totalshouldCoerceToNumber
constant that expresses the action we need to take:function add(...thingsToAdd: (string | number)[]): number {
let total = 0;
for (const thingToAdd of thingsToAdd) {
const shouldCoerceToNumber = typeof thingToAdd === 'string';
if (shouldCoerceToNumber) {
total += Number(thingToAdd);
} else {
total += thingToAdd;
}
}
return total;
}
console.log(add(1, '7', '3', 9))
Operator '+=' cannot be applied to types 'number' and 'string | number'.(2365)
shouldCoerceToNumber
represents a type narrowing of thingToAdd
from string | number
to string
. So the type of thingToAdd
remains unchanged from string | number
when we write code that depends upon it.thingToAdd
variable has been narrowed to a string
. This is because control flow analysis of aliased conditions is now in play.