|
|
|
|
|
by scambier
1204 days ago
|
|
You seem knowledgeable about TypeScript, so you certainly very well understand what people mean by "types are not available at runtime". Once your typescript is compiled to javascript, there's nothing left of your user-defined types and interfaces. Type guards are a security that is very much a workaround for the lack of types at runtime. |
|
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...