I’ve been writing some unit tests in TypeScript. The example QUnit test contains:
ok( 1 == "1", "Passed!" );
The tsc compiler claims that:
Operator ‘==’ cannot be applied to types ‘number’ and ‘string’
And exits with status 1 (although it does correctly produce the JS).
The spec says:
The <, >, <=, >=, ==, !=, ===, and !== operators
These operators require one operand type to be identical to or a subtype of the other operand type. The
result is always of the Boolean primitive type.
So it looks like the warning / error is correct. Doesn’t this rather defeat the point of the type coercing == operator though? Is there ever a valid use case for using == in TypeScript that won’t produce this warning?
At least one probable scenario for
==(i.e., with type coercion) in TypeScript is when one of the expected operands is of Any type:Now you probably see the picture: any function that has an Any param can safely (well, more-o-less; all the common gotchas of
==are still applied here) compare it with value of any set type with==.