How do I validate my API response when storing it as an object. For example:
const { data } = await axios.get("/form");
How do I make sure this data conforms to:
interface Form {
title: string;
questions: Question[]
}
How do I validate my API response when storing it as an object. For example:
const { data } = await axios.get("/form");
How do I make sure this data conforms to:
interface Form {
title: string;
questions: Question[]
}
Typescript does not perform any type of validations out of the box like java or other strongly typed languages.
Things like
const { data } = await axios.get<Form>("/form");
does not guarantee that the response data is of Form type. It is just used for static typing checks (no errors/validation in runtime). For having a guarantee I would recommend the implementation of a guard function with some JSON schema validation. For example, you can use https://www.npmjs.com/package/ajv or https://www.npmjs.com/package/joi package to do that.
Use:
const { data } = await axios.get<Form>("/form");
If you want to make sure that the incoming data is indeed compatible with Form interface, you have to do it in runtime (thus can't be done with TS). Checking runtime data is compatible with a type isn't always straightforward or easy (especially with nested data). io-ts is one of the libraries that does it.