Skip to content

Exhaustive switch return type is incorrect without intermediate variable #34661

Closed

Description

@niedzielski

TypeScript Version: 3.7.0-beta

Search Terms: enum switch

Code

enum Animal {
    DOG,

    // Add second member to avoid https://github.com/microsoft/TypeScript/issues/23572.
    CAT
}

const zoo: { animal: Animal } | undefined = { animal: Animal.DOG }

// OK.
function intermediateVariable(): Animal {
    const animal = zoo?.animal ?? Animal.DOG
    switch (animal) {
        case Animal.DOG: return Animal.DOG
        case Animal.CAT: return Animal.CAT
    }
}

// Error: Function lacks ending return statement and return type does not include 'undefined'.(2366)
function expression(): Animal {
    switch (zoo?.animal ?? Animal.DOG) {
        case Animal.DOG: return Animal.DOG
        case Animal.CAT: return Animal.CAT
    }
}

Expected behavior: Inferred type doesn't depend on intermediate state.

Actual behavior: Inferred type differs when an expression is switched on directly versus when the value is assigned to an untyped intermediate variable and then switched on.

Playground Link

Related Issues: #6155 #32905

Activity

  1. added
    BugA bug in TypeScript
    and removed
    Needs InvestigationThis issue needs a team member to investigate its status.
    on Oct 30, 2019
  2. ahejlsberg commented on Oct 30, 2019

    @ahejlsberg
    Member

    This issue is an effect of switching to the control flow analyzer for exhaustiveness checking. We need to unconditionally include CFA nodes representing a missing default clauses in order for our analysis to be correct. Currently we only include such CFA nodes when the switch expression is a narrowing expression.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions