Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Equals (==) in TypeScript

Tags:

typescript

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?

like image 961
RichardTowers Avatar asked Dec 19 '12 12:12

RichardTowers


People also ask

What is == in TypeScript?

The Typescript has two operators for checking equality. One is == (equality operator or loose equality operator) and the other one is === (strict equality operator). Both of these operators check the value of operands for equality.

What is the difference between == and === in TypeScript?

== is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.

What is double == in JavaScript?

Double Equals ( == ) checks for value equality only. It inherently does type coercion. This means that before checking the values, it converts the types of the variables to match each other.

What is == and === in JavaScript?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.


1 Answers

At least one probable scenario for == (i.e., with type coercion) in TypeScript is when one of the expected operands is of Any type:

A type S is a subtype of a type T, and T is a supertype of S, if one of the following is true: [...]

T is the 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 ==.

like image 195
raina77ow Avatar answered Sep 27 '22 18:09

raina77ow