Skip to content

TypeScript reports incorrect errorΒ #61563

@johndeighan

Description

@johndeighan

πŸ”Ž 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

https://www.typescriptlang.org/play/?ts=5.9.0-dev.20250410#code/EQVwzgpgBGAuBOBLAxrYBuAUMg9gOzigBsARAQ1jIC4oAKPEAWwCMJ4oAfGBRPAc05QQeACYQAZrwgiAlAG0AulAC8UOZgCQAFgBMAGk0ByMs2SGDG4WMl5pmhZmz5CRAEo4A7jThJ+ilcTklAB0jGQADrS0iLAQjDIqAHxQAN6aiOJ0MXEqyqpWElKyUPAQsCDweFCGhlgaGXSwAJ7hEDiZ2Yy5qoYMLGyGCaXllVCdwbA4AGKIAB7StDoydQ20za3tY7FdeT0+vHyDJWUVVZ1YAL4yjrgEOEQQwSKI8LRuntdAA

πŸ’» 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

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions