|
That isn’t what TypeScript is for, you’re describing a similar but unrelated problem, namely runtime type validation. There’s a reason why JSON.parse() returns any.
However. TS allows to avoid logical errors in the program's source, which is a class of errors historically very important, since JavaScript is so highly dynamic. The debug mode sounds interesting at first thought, but quickly explodes in complexity when you deal with more complex object types and signatures. To enable automatic runtime validation for all cases, you would need to rewrite programs so thoroughly that you’re pretty much guaranteed to introduce bugs and behaviour changes that were not present in the source code. In my opinion it’s great that TS draws a strict boundary to avoid runtime impact at all cost, and leave that to libraries like Zod, which handle dealing with external data. > to catch all the "somebody fetched a wrong type from the backend" or "someone did some stupid ((a as any) as B) once to silence the compiler and now you can't trust any type assertion about your codebase" problems. Nada. Those type casts are sure annoying, but what’s the alternative? Even in your hypothetical debug mode, you would not be safe here, since you’re effectively telling the compiler you know better and it’s supposed to transform that type, not assert it. Or do you want to remove the escape hatch „as“ is? Because that would be a major pain in the ass in situations where you just do know better, or don’t want to ensure perfect type safety for something you know will work. You can’t make things idiot proof, no matter how hard you try. That doesn’t make preprocessing type hints useless. |
The closest thing to JavaScript would probably be Dart, now that it has sound types [1].
You’re right that it’s a pain in some situations.
[1] https://dart.dev/language/type-system