4 ms·
one thing I wish typescript had was an ability mark typechecks as runtime. Commonly I'll have a nodejs express app which serves an api and i've love a easy way
by anko 9y ago
one thing I wish typescript had was an ability mark typechecks as runtime.
Commonly I'll have a nodejs express app which serves an api and i've love a easy way to validate an interface against the payload passed in. Maybe it would be as simple as a function JSON.parseWithChecking<User>(payload) or some annotation to get the interface reflected and passed into this function at runtime. It's normally always at deserialisation that this problem occurs.
- dean177 9y agoI do this with a custom jasmine matcher in integration tests, you provide the matcher with some objects (which all satisfy the type you are expecting) and the matcher tells you if the response satisfies the type. It's a bit rough around the edges, but has been very useful so far. I'd consider creating an npm module if there is interest.
- whatever_dude 9y agoWouldn't it be better to use a JSON Schema validator in this case?
- anko 9y agoThen you're maintaining two definitions - typescript ones and json schema ones. But thanks for the idea :)
- whatever_dude 9y agoWell, you could have one or the other and then just convert a schema to an Interface [1], or vice versa [2]. The reason I like schema-first is because a schema allows you to be way more strict about what's accepted in most cases, e.g. validating an entry via RegEx. It tends to make APIs safer and runtime errors more clear. [1] https://github.com/bcherny/json-schema-to-typescript https://github.com/bcherny/json-schema-to-typescript [2] https://github.com/YousefED/typescript-json-schema https://github.com/YousefED/typescript-json-schema
- gcanti 9y agoYou could write the runtime definition and extract the static types from that https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts
- anko 9y agothanks for the link - i've never seen that before :)
- ng12 9y agoWell you need both right, the Typescript interface and the JSON Schema? There's still the possibility of a mismatch there.