最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - give response a type of fetch response in typescript? - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question asked Nov 23, 2021 at 16:03 Alicia YAlicia Y 3871 gold badge6 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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[]
}
发布评论

评论列表(0)

  1. 暂无评论