Skip to content
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

Union with enum does not consider all code paths #25195

Closed
methyl opened this issue Jun 25, 2018 · 2 comments
Closed

Union with enum does not consider all code paths #25195

methyl opened this issue Jun 25, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@methyl
Copy link

methyl commented Jun 25, 2018

TypeScript Version: 3.0.0-dev.20180623

Search Terms:
enum union code paths
Code

enum Foo {
    One = "ONE",
    Two = "TWO",
}

type Bar = Foo | number

function test(bar: Bar): number {
    if (typeof bar === 'number') {
        return bar
    } else {
        switch (bar) {
            case Foo.One:
                return 1
            case Foo.Two:
                return 2
        }
    }
}

Expected behavior:
No error since all code paths are covered (Bar is number, Bar is one of [One, Two])

Actual behavior:

test.ts:15:26 - error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

This works:

enum Foo {
    One = "ONE",
    Two = "TWO",
}

type Bar = Foo

function test(bar: Bar): number {
    switch (bar) {
        case Foo.One:
            return 1
        case Foo.Two:
            return 2
    }
}

**Playground Link:**http://www.typescriptlang.org/play/#src=enum%20Foo%20%7B%0D%0A%20%20%20%20One%20%3D%20%22ONE%22%2C%0D%0A%20%20%20%20Two%20%3D%20%22TWO%22%2C%0D%0A%7D%0D%0A%0D%0Atype%20Bar%20%3D%20Foo%20%7C%20number%0D%0A%0D%0Afunction%20test(bar%3A%20Bar)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(typeof%20bar%20%3D%3D%3D%20'number')%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20bar%0D%0A%20%20%20%20%7D%20else%20%7B%0D%0A%20%20%20%20%20%20%20%20switch%20(bar)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20case%20Foo.One%3A%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%201%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20case%20Foo.Two%3A%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%202%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%7D%0D%0A%7D

@ghost
Copy link

ghost commented Jun 25, 2018

Duplicate of #20823 -- try adding an assertNever helper.

@ghost ghost added the Duplicate An existing issue was already created label Jun 25, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants