|
|
|
|
|
by rewma
1715 days ago
|
|
> Presumably the GP's data is external and therefore not checkable or inferrable by typescript. There is no such thing as external data that is not checkable or inferable by typescript. That's what type assertion functions and type guards are for. With typescript, you can take in an instance of type any, pass it to a type assertion function or a type guard, and depending on the outcome either narrow it to a specific type or throw an error. |
|
> inferring types from any object is a trivial task
This is true for values defined in code, but TypeScript cannot directly see data that comes in from eg. an API, and so can't infer types from it. You can give the data types yourself, and you can even give it types based on validation logic that happens at runtime, and I think this is usually worth doing and not a huge burden if you use a library. But it's disingenuous to suggest that it's free.
The closest thing to "free" would be blindly asserting the data's type, which is very dangerous and IMO usually worse than not having static types at all, because it gives you a false sense of security:
The better approach is to use something like io-ts to safely "parse" the data into a type at runtime. But, again, this is not without overhead.