|
|
|
|
|
by eyelidlessness
1200 days ago
|
|
I’m encouraging thinking about the problem from a different angle. If you parse rather than validate[0][1], you have roughly all of the type information you could want in the runtime, and by using type guards the type system will reflect the runtime types. It’s not a workaround. Every language with runtime types will have some logic devoted to this kind of casting/narrowing. TypeScript rightly doesn’t build it into the compiler because most of the time you don’t want types to have runtime behavior. For internal logic which can be validated statically, runtime types would be an unnecessary overhead. So it’s up to developers to determine where it should be applied. Type guards are explicitly an affordance for that, designed specifically to convey types with runtime casting/narrowing. If you use good, composable primitives like zod or io-ts or any of several other implementations, your code will typically be almost identical to deriving runtime from types rather than the inverse. 0: https://itnext.io/parse-dont-validate-incoming-data-in-types... 1: https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va... |
|