2 ms·
It should be possible to implement the instanceof operator for arbitrary types using essentially the same logic as the type checker. (Caveat: I don't know wheth
by yorwba 9y ago
It should be possible to implement the instanceof operator for arbitrary types using essentially the same logic as the type checker. (Caveat: I don't know whether any TypeScript-specific properties make this impossible, since I have never used it.)
For each object, there is some function that takes no input and returns that object, by simply constructing the recursion-free parts of the object graph and then filling in any cycles. (TypeScript allows mutation, right?)
Then the question of `x instanceof Foo` becomes "is the function returning x typeable as () -> Foo". Of course that check is going to be much much more expensive than the simple comparison of the class tag other languages use, so I can understand why it's not part of the language.
- wtetzner 9y agoThe type checker has access to the source code (and any type annotations). That information isn't available at runtime, so I'm not sure how you'd be able to run the type checker at runtime.
- yorwba 9y agoYou don't need the original source code, any code producing the object you want to check will do. If the object has a field "field" with value "value", then the code function () { return {field: "value"}; } produces a value of type Foo precisely when the original object was of type Foo, even if the code producing it was much more complex. I don't see why that wouldn't work. If you have a specific example where that approach fails, I'd like to know about it.
- wtetzner 9y agoBut I don't know where you'd get that source code from at runtime though? I'm sure there are languages that contain enough runtime information, but, as an pertinent example, there isn't a way to tell that you have an object with certain fields in OCaml at runtime. It's just a block at runtime. All of the names are gone, as they were only used at compile time.
- yorwba 9y agoI was assuming the TypeScript/JavaScript scenario, where TypeScript objects are implemented as JavaScript objects and their structure is available at runtime. Of course it does not work if you do not have that reflection capability.
- lilactown 9y agoYou can provide your own type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html https://www.typescriptlang.org/docs/handbook/advanced-types.... Doing this in the general case, I assume, is probably not practical.