-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed as not planned
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
type narrowing
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing
β― Playground Link
π» Code
"use strict";
const lData: (number | string | undefined)[] = [
42,
'abc',
undefined
]
const lRow: string[] = lData.map((item) => {
if (item === undefined) return '';
if (typeof item === 'number') return item.toFixed(2);
if (typeof item === 'string') return item;
})
console.dir(lRow)```
### π Actual behavior
The above code results in errors, even though the mapping function being used can never return an undefined value. Oddly, if I use a switch statement instead of a series of if statements, no errors are reported:"use strict";
const lData: (number | string | undefined)[] = [
42,
'abc',
undefined
]
const lRow: string[] = lData.map((item) => {
switch(typeof item) {
case 'undefined': {
return '';
}
case 'number': {
return item.toFixed(2);
}
case 'string': {
return item;
}
}
})
console.dir(lRow)
### π Expected behavior
There should be no errors in either case since the items being mapped over can only be undefined, a string or a number. Note that in both of the examples, there is no "else" case.
### Additional information about the issue
_No response_
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created