Should I write out the JSON structure of an api call as an interface in typescript to interact with values inside response?

Viewed 52

So i'm just starting out with typescript and something that I can't find much info on is how to deal with types for api call responses.

Lets say, I make a GET request to an api and it returns a JSON object for example:

{
 name: "john",
 age: 12
}

in my code, if i wanted to interact with response.name would i have to create an interface like below to use response.name without having a red linter under it?

interface Response {
 name: string,
 age: number 
}

or is there a easier way to do it as some api calls would return JSON > 10 lines long and copying out the whole structure for every type of call seems very troublesome. Another thought I had was to create the interface but only have values I would use instead of the whole structure, but i'm not too sure so any help would be greatly appreciated!

1 Answers

You can define Response as a "common" type, that supports all types of API json response.

interface IResponse {
  [key: string]: any
}

Now, you can type response.name without the "red line", also response.not_exist_property is valid.

My recommendation is to define all types for all API response type:

interface GetUserResponse {
  name: string,
  age: number,
}

for GET /users/:id (example)

You can use this tool to convert a json response to Typescript type.

Related