|
|
|
|
|
by tomaskafka
426 days ago
|
|
TS: "We have added types to javascript, everything is now strongly typed, and the compiler will pester you to no end until it's happy with the types." Me: "Awesome, so I get an object from an API, it will be trivial to check at runtime if it's of a given type. Or to have a debug mode that checks each function's inputs to match the declared types. Otherwise the types would be just an empty charade. Right?" TS: "What?" Me: "What?" Realizing this was a true facepalm moment for me. No one ever thought of adding a debug TS mode where it would turn function myFunc(a: string, b: number) {} into function myFunc(a: string, b: number) {
assert(typeof a === "string")
assert(typeof b === "number")
} 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. |
|
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.