Skip to content

Switch statement starts generating "Not all code paths return a value" when wrapped in try/finally #19423

Closed
@mattmccutchen

Description

@mattmccutchen

I was confused when my function suddenly started to generate a "Not all code paths return a value" error when I put a try/finally statement around an enum switch statement. After reading #17358 (comment) and #9163 (comment), I understand it's a limitation of the current implementation that the exhaustiveness check only works for a switch statement that's the last thing in a function. This information wasn't trivial for me to find, so I'm filing an issue that the next person will hopefully be able to find more quickly, as well as to provide feedback that I found the inconsistency confusing.

In my opinion, ideally the exhaustiveness check should apply whenever the switch statement has a control-flow successor that has another antecedent. The important thing is that it should not apply when the switch statement is immediately followed by an unconditional statement, suggesting developer intent that the switch statement not be considered exhaustive. But this can be a naive check just based on the kind of the immediately enclosing control structure.

TypeScript Version: reproduced with master as of this writing (ceba507)

Code

// Compile with --noImplicitReturns

enum Test {
  ONE = 1,
  TWO = 2
}
function mySwitch(t: Test) {
  switch (t) {
    case Test.ONE:
      return 42;
    case Test.TWO:
      return 42;
  }
}
function mySwitchWrapped(t: Test, b: boolean) {
  try {
    switch (t) {
      case Test.ONE:
        return 42;
      case Test.TWO:
        return 42;
    }
  } finally {}
}

Expected behavior:
Consistent exhaustiveness checking for mySwitchWrapped and mySwitch.

Actual behavior:
"error TS7030: Not all code paths return a value." on mySwitchWrapped, but not on mySwitch.

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