Typescript API Validation
Consuming APIs
- The JSON value might not be an object at all.
- It might be null, which is an object in JavaScript but not the kind of object we expect.
- It might not have the properties that are expected.
- It might have the properties, but with unexpected types.
Must choose the level of safety when validating outside data:
With no safety at all this means using any, or forcing the type with parsed as Comment. If the runtime data is wrong, you can't tell, just as with JavaScript.
Implement checks manually. This gives us good confidence, but requires a lot of extra code for detailed API with deeply nested objects!
Implement checks with a third-party data validation library like io-ts or runtypes. This gives greatest confidence and requires less code. The trade-off is learning how to use the library.
The best option depends on risk. For financial, healthcare or user authentication and authorization then apply strict, formalized checks on all data.
For an internal analytics dashboard, where bugs won't be visible to customers and can't cause incorrect data to end up in a database it may be fine to use any or as to skip the data validation.
JSON.parse dangerous as it has a return type of any. It's best to explicitly specify the unknown type
const parsed: unknown = JSON.parse(json).