3 ms·
The 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
by wtetzner 9y ago
The 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.