2 ms·
1. Use discriminated union types: https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions https://www.typescriptlang.org/docs/hand
by rictic 7y ago
1. Use discriminated union types: https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions https://www.typescriptlang.org/docs/handbook/advanced-types.... - TypeScript these days sticks with the runtime semantics of JavaScript, and discriminated unions are a very natural way to express algebraic data types in JS.
2. Use https://github.com/YousefED/typescript-json-schema https://github.com/YousefED/typescript-json-schema to generate a JSON schema, then use a json schema validator to do runtime validation. That's how https://github.com/Polymer/tachometer https://github.com/Polymer/tachometer handles config file parsing and it works very well.
- noncoml 7y agoMy only problem with 1. is that it desn’t work that well with Error
- azangru 7y agoAlso, (1) won’t be exhaustive.
- alangpierce 7y agoThere are a few ways to get exhaustiveness checking in TypeScript when using tagged unions. The way I usually do it is an assertNever function like this: function assertNever(value: never): any { return value; } Then if you call assertNever on your variable in the default switch case or the last else block, TypeScript will error if you didn't handle every case, since it expects the variable to have been narrowed to the "never" type since there's no remaining value that it can take on. That's also a good place to do a runtime check since TS types aren't guaranteed to match runtime values.