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

Lostfields picture Lostfields · Aug 31, 2016 · Viewed 42.7k times · Source

TypeScript Version: 2.0.2.0

Code I know the code is a bit stupid, but I actually have these kind of tests in my code (making an expression visitor) and I really think these should fly and compile right away.

var a: boolean = (true == false);
var b: boolean = (5 == 2);

Instead it complains that operand equal cannot be applied to types 'true', 'false', '5' and '2'. Mark that they are not boolean or number, they are actually a types of 'true','false','5','2'. I know that types 'string' and 'boolean' cannot be compared, but hey, 5 is actually a number, not type '5' or am I mistaken?

This compiles though.

let x = 2;
var a: boolean = 5 == x;
var b: boolean = <number>5 == <number>2;

Am I missing something, why arent't 5 and 2 considered as type 'number' ?

Expected behavior: Should compile

Actual behavior: Results in a compile error saying 'Operand '==' cannot be applied to types '<first argument>' and '<second argument>'

Background I came over this issues in typescript defining that it should be like this, but how come? https://github.com/Microsoft/TypeScript/issues/6167

Answer

Simon Meskens picture Simon Meskens · Aug 31, 2016

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.