#Number === String -> Error, Class1 === Class2 -> No error?

5 messages · Page 1 of 1 (latest)

wind halo
#

Why does the type checker show an error when comparing Number === String, but not when comparing two classes that I've defined myself.

class Class1 {};
class Class2 {};

console.log(Class1=== Class2) // No error?
console.log(Number === String) // Error

And how could I get it to throw an error?

surreal light
#

There are two things at play here:

  • TS is structurally typed, so typeof Class1 and typeof Class2 are structurally equivalent, because they are both class constructors that construct an instance with no property.
  • When doing a === b comparison, TS does a basic overlap test to prevent obvious errors.
#

In the case of Number === String, typeof Number and typeof String have no overlap, so TS deduces that you are probably making an error because this comparison doesn't make sense.

#

For the case of Class1 === Class2, typeof Class1 and typeof Class2 are equivalent like explained in point 1, so TS isn't sure it's a mistake.

#

If you just give Class1 and Class2 some properties, they will stop being structurally equivalent, and TS will warn you about it again.