give response a type of fetch response in typescript?

Viewed 2657

I have this in my list.json

[{"id": "1", "qty": 1}]

I call it via fetch

async function fetchPlaces() {
  let response = await fetch(`./data/list.json`);
  response = await response.json();
}

how can make the response same type as the interface?

IList {
   id: string,
   qty: number
}

I tried response = await response.json() as IList[] it doesn't work

1 Answers

The problem is that you are reusing the response variable, which is inferred to be of type Response (which is what fetch returns)

The following works:

interface IList {
   id: string,
   qty: number
}

async function fetchPlaces() {
  let response = await fetch(`./data/list.json`);
  let decoded = await response.json() as IList[]; // type is IList[]
}
Related