5 ms·
While I understand the purpose of TypeScript's type erasure, I kinda wish there was an opt-in type reification so that type guards could be automatically create
by _hardwaregeek 8y ago
While I understand the purpose of TypeScript's type erasure, I kinda wish there was an opt-in type reification so that type guards could be automatically created. I don't really like how they rely on the user to get runtime type assertions correct. But I guess then there'd have to be a TS runtime of sorts.
- recursive 8y agoOne of the guiding principles of Typescript is that it compiles to javascript. There isn't really a generally correct and practical way to do arbitrary type checking at runtime. For many types there is, such as using `instanceof` or `typeof`, but those don't work for testing interface compliance. Also, any type with a generic parameter is going to be hit-or-miss.
- seanmcdirmid 8y agoNot just compiles to JavaScript, it compiles simply via type erasure and lacks a runtime.
- deleted 8y ago[deleted]
- yawaramin 8y agoNot necessarily. ML-family languages which compile to JS, like ReasonML, can encode sum types in a variety of ways. (Sum types are essentially type reification because the alternative cases are 'tagged' with names). Tag encoding can be quite clever. For example, ReasonML's BuckleScript compiler can encode a sum type like this: type chequeNum = string; type paymentMethod = | Cash | Cheque(chequeNum); ... as the number 0 for the `Cash` case and as a single-element array for the cheque case. See e.g. https://reasonml.github.io/en/try.html?rrjsx=true&reason=C4TwDgpgBAxgFhAjgVwgOWQWygXigZ2ACcBLAOwHMBuAKFEijAEMRMIzgBZCYOAewAmuGgB8oAYSb44oiQhQQAFPCSoMmAJS0aAGx5RgfAMrFyFXFABmyMjShQxk6bgB8UAEQAFJiSHlYUnDudg5yqkoqCuoarlAA3gBWIt6+UADuJLyw8qhQZHwAdFAAJJFqWCIJAL7aesAB0t6s7PV4TnC0ddnhTWwcFuI5Su4AjABMAMwALO5aNEA https://reasonml.github.io/en/try.html?rrjsx=true&reason=C4T...
- skrebbel 8y agoAgree. It would be awesome if TypeScript had some optional run-type information, maybe in the form of a decorator function @rtti function moo(foo: string): number { … } => function moo(foo: string): number { … } moo.__type = { parameters: [{name: "foo", type: "string"}] returnType: "number" } or something like that.
- lf-non 8y agoio-ts[1] is a great solution for implementing runtime-types. The most interesting feature is that the static type can be "extracted" out of the runtime type so in most cases there is no duplication of information between runtime type and static type. [1] https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts
- knocte 8y agoBINGO! I suggested this to typescript repo: https://github.com/Microsoft/TypeScript/issues/28337 https://github.com/Microsoft/TypeScript/issues/28337 Feel free to comment on it, but it seems it's impossible that they implement such kind of thing without breaking their "principles".