Skip to content

Exhaustive switch return type is incorrect without intermediate variable #34661

@niedzielski

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

Metadata

Metadata

Assignees

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions