Skip to content

Incorrect error generated when comparing enum values. #10989

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
dbaeumer opened this issue Sep 19, 2016 · 5 comments
Closed

Incorrect error generated when comparing enum values. #10989

dbaeumer opened this issue Sep 19, 2016 · 5 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@dbaeumer
Copy link
Member

TypeScript Version: 2.0.2
Code

enum Direction {
    LEFT,
    RIGHT
}

function bug(direction?: Direction): number {
    if (!direction) {
        return 10;
    } else {
        return (direction === Direction.LEFT) ? 10 : 0;
    }
}

You get a compile error saying the Direction can't be used in ===. This is IMO incorrect.

@mhegazy
Copy link
Contributor

mhegazy commented Sep 19, 2016

Direction.LEFT is 0, it will be filtered out in !direction check. so the only value direction could have in the else clause is Direction.RIGHT; and Direction.RIGHT will never be Direction.LEFT.

So depending on what is the intent here, either make LEFT non-false:

enum Direction {
    LEFT = 1,
    RIGHT
}

or just trust that this will produce the same result:

    if (!direction) {
        return 10;
    } else {
        return  0;
    }

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Sep 19, 2016
@dbaeumer
Copy link
Member Author

You are absolutely right and that error actually catches a problem in our code. JS falsy ....

@dbaeumer
Copy link
Member Author

Closing.

@basarat
Copy link
Contributor

basarat commented Sep 20, 2016

JS falsy

I've had this happen to be even before it was an error. Hence : https://basarat.gitbooks.io/typescript/content/docs/enums.html#changing-the-number-associated-with-an-enum I added I quite commonly initialize the first enum with = 1 as it allows me to do a safe truthy check on an enum value. Can help fix that error quickly ;) 🌹

@forthedamn
Copy link

I encountered the same situation, and solved in same way.

initialize the first enum with = 1

That will be great!

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants