-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed
Description
Consider the following code
function test4(value: 1 | 2) {
let x: string;
switch (value) {
case 1: x = "one"; break;
case 2: x = "two"; break;
}
return x; //There is no path through the switch so x is alwayes assigned here.
}
Expected behavior:
The code should type check under --strict
Actual behavior:
Definite assignment does not realize that the switch is exhaustive and that all paths assign to x, so we get an error.
Checked with 2143a3f
SlurpTheo
Metadata
Metadata
Assignees
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
DanielRosenwasser commentedon Dec 20, 2017
The problem is that definite assignment doesn't take types into account, it just works on the control flow graph. Adding a
default: throw new Error("...");
should do the trick though.ghost commentedon Dec 20, 2017
Internally we use (simplified)
default: throw assertNever(value);
withantialize commentedon Dec 20, 2017
I use that as well. Note however that
Will not work due to #20822
ghost commentedon Dec 20, 2017
Yeah, that's why you have to write
throw assertNever(value);
to indicate to control flow that it never returns.Jessidhia commentedon Dec 22, 2017
not
return assertNever(value)
?I do use a similar helper in my code, which I called
unreachable
.ghost commentedon Dec 22, 2017
The function's never going to finish evaluating either way, so it doesn't really matter whether you
return
orthrow
the result -- just a style preference.DanielRosenwasser commentedon Dec 22, 2017
Armchair perf speculation:
return
probably won't trigger a de-opt.typescript-bot commentedon Jan 6, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
methyl commentedon Jun 26, 2018
@Andy-MS is this something you plan to tackle in the future?