Operator ‘==’ cannot be applied to types x and y in Typescript 2

Literal types have many advantages, as it lets the compiler make types as narrow as possible. Your use case is one that comes up very rarely, but wanting types to be as narrow as possible permeates the entire design of the language. So yes, while it makes your life harder in this one specific case, it makes sense in the language as a whole. Users would have to suffer a significantly worse language, just to support this one rare use case.

Unfortunately, you will have to use the explicit typing you suggest yourself in the second example. I don’t see this ever being fixed, because the majority of users wants the language to yell if they try to do this. It’s probably the sign of a bug in a large majority of cases.

Leave a Comment