1

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[]
}
1
  • 2
    Using typescript? You can't, it doesn't exist at runtime. Commented Mar 29, 2021 at 20:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

P.S. there are packages that allow generating interfaces from JSON schemas npmjs.com/package/json-schema-to-typescript. P.P.S. the same JSON schemas may be shared between BE and FE validators. And a lot of devs interpreter JSON schemas as a guarantee (contract) which is the source of truth.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.