TypeScript: Error "Operator '===' cannot be applied to types" with enum type
TypeScript Version: 2.0.3
Code
enum SomeEnum {
V1,
V2
}
class SomeClass {
protected state:SomeEnum
method() {
// "Operator '===' cannot be applied to types 'SomeEnum.V1' and 'SomeEnum.V2'." error here
this.state = SomeEnum.V1
if (this.state === SomeEnum.V2) {
}
// and the same error here
if (SomeEnum.V1 === SomeEnum.V2) {
}
// but no error here
let state2 = SomeEnum.V1
if (state2 === SomeEnum.V2) {
}
}
}
Expected behavior: I didn’t expect that error in these cases
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 22 (7 by maintainers)
enum values starts with
0so in your codeSortOrder.NONEwill have numeric value0. First part of the checkorder && order !== SortOrderNonealready rules out falsy values so second partorder !== SortOrder.NONEeffectively becomes useless since it is always trueThe errors are actually the intended behavior. In the first example the compiler knows that
this.statehas the valueSomeEnum.V1and therefore the comparison will always be false. The second example is just another way of demonstrating that. The third example actually should be an error and is an error in the nightly builds (see #10676 for more detail on what changed here).In my case I used a switch instead of if/else, it worked without any error.
@effzeh somehow this issue hasn’t linked to #9998 yet, but see the first example there. Short answer: add a type assertion, or change
toktogetToken()I’m getting the same error with the following code (
tsc version 2.1.5)I just started learning JavaScript/TypeScript, so it’s very likely I’m missing something, but that this code works in one case and not in the other just doesn’t seem right to me. (This is a reduced test-case from a port of a small C++ JSON parser to TypeScript. The generated JS code for the larger parser works as intended.)
@vladima As you are right, such compile error is bug. When enum member is represented by number i should be able to compare number type with === or !===
Maybe it has something to do with generators/yield.
Sample:
Save file as “ts-enums.ts” and compile with:
tsc ts-enums.ts -t ES2015And you got error:
error TS2365: Operator '===' cannot be applied to types 'State.Initializing' and 'State.InitSuccess'Typescript version: 2.0.3