What is the best way doing cross-realm type checking in JavaScript?
Asked Answered
G

1

6

I'm currently building a type checking library that supports checking variables from another realm (a.k.a. different context).

For basic types like string and number, I can simply use the typeof operator as usual.

For complex types like Date instance, the only way to make it work is to use Object.prototype.toString.call() method. But this method has its problem, I have to iterate through the prototype chain of the instance if the Symbol.toStringTag property was overridden.

The question is, should I iterate through the prototype chain of the instance if the value returned by Object.prototype.toString.call() doesn't match in the first time?

Giesecke answered 7/6, 2020 at 7:50 Comment(2)
Why can you not use instanceof?Zackzackariah
@Zackzackariah It's because instanceof not work with variables from another realm.Giesecke
P
1

The best way is with protocols, something JS has a proposal for but has yet to implement. I have a library that implements protocols and broaches the cross-realm issue.

https://github.com/mlanza/atomic

You are correct, that instanceof cannot work. Protocols are defined. Then the protocols, being behaviors, are applied to the same types in different realms. These shared behaviors become the basis of your programming and type checking.

Even with protocols, there's no magic to get this to happen automatically. One has to recognize a new script/module is in another realm and apply the same behaviors/protocols there. Effectively, one has to patch each known realm to make them interoperable.

Then one uses a protocol ako, for example, instead of instanceof. Having patched all the realms, one could ask...

_.ako(tvshows, Array) // => true

...and anticipate a reliable answer. Sorry it's not easier, but it's not a common enough problem for the experts to have worked out better answers.

Petuu answered 29/5 at 13:55 Comment(2)
What does ako mean?Bwana
ako a kind of. The other option is is. So an inherited type or direct type equality.Petuu

© 2022 - 2024 — McMap. All rights reserved.