Hacker News new | ask | show | jobs
by Sahhaese 2559 days ago
Typescript only checks all that at compile time though. The complaint here is that even a typed json.Parse<T> :(json:string)=>T will not actually give any type checking when you pass it a string containing any schema.
3 comments

When you type json.Parse<T> you are taking on the responsibility that what is returned is actually T. If you want the type checker's help that you are sure it might not be T, then ask for it: json.Parse<unknown> or json.Parse<Partial<T>> is maybe more accurate, and would force you to write runtime checks. Partial<T> in particular is a great helper type that is often exactly what a lot of want in a json.Parse situation: gives you the field autocomplete you want, but reminds you that they may be undefined.
A sound type system shouldn't allow you to write such a parser function without either you lying in its implementation or having to use unsafe code.

In a year or two, once everyone has switched to use `unknown` instead of `any` in functions which at runtime return… uhm… unknown values, we'll all be much safer. Because we'll be forced to use proper parsers and validators.

And that's what `runtypes` provides.