microsoft / microsoft/TypeScript
narrowing to "never" by "if" statement does not exclude "undefined" return type
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 2.7.1
Search Terms: narrowing types never switch case if undefined strictNullChecks
Code
// Build this code with "--strictNullChecks" option.
function assertNever(x: never): never {
throw new Error("not reached");
}
enum A {
Foo, Bar
}
// There are no errors on this function.
function good(a: A): number {
switch (a) {
case A.Foo: return 0;
case A.Bar: return 1;
}
}
// This function causes the following error though "a" is "never" at the end of the function.
// error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
function bad(a: A): number {
if (a === A.Foo) return 0;
if (a === A.Bar) return 1;
}
// No error if explicit return of "never" is added.
function ok(a: A): number {
if (a === A.Foo) return 0;
if (a === A.Bar) return 1;
return assertNever(a);
}
Expected behavior: The bad() function should not cause error so that if statement works like switch.
Actual behavior: As commented in the code, only bad() function causes an error.
Playground Link: (please check "strictNullChecks" option.)
Related Issues:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the issue's TypeScript code with strictNullChecks enabled and compare the if and switch cases. Trace the compiler's control-flow narrowing and missing-return analysis for the bad function. Done means the reported diagnostic is resolved for this case and regression coverage confirms the behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100