Skip to content

Exhaustive switch return type is incorrect without intermediate variable #34661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
niedzielski opened this issue Oct 23, 2019 · 1 comment · Fixed by #34840
Closed

Exhaustive switch return type is incorrect without intermediate variable #34661

niedzielski opened this issue Oct 23, 2019 · 1 comment · Fixed by #34840
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@niedzielski
Copy link

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

@RyanCavanaugh RyanCavanaugh added the Needs Investigation This issue needs a team member to investigate its status. label Oct 30, 2019
@RyanCavanaugh RyanCavanaugh added this to the TypeScript 3.8.0 milestone Oct 30, 2019
@ahejlsberg ahejlsberg added Bug A bug in TypeScript and removed Needs Investigation This issue needs a team member to investigate its status. labels Oct 30, 2019
@ahejlsberg
Copy link
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants