在打字稿中为响应提供一种获取响应类型?

Ali*_*a Y 6 javascript typescript reactjs

我的 list.json 中有这个

[{"id": "1", "qty": 1}]
Run Code Online (Sandbox Code Playgroud)

我通过 fetch 调用它

async function fetchPlaces() {
  let response = await fetch(`./data/list.json`);
  response = await response.json();
}
Run Code Online (Sandbox Code Playgroud)

如何使响应与接口类型相同?

IList {
   id: string,
   qty: number
}
Run Code Online (Sandbox Code Playgroud)

我尝试了response = await response.json() as IList[]没用

Tax*_*xel 3

问题是您正在重用该response变量,该变量被推断为类型Response(这就是fetch返回的类型)

以下作品:

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[]
}
Run Code Online (Sandbox Code Playgroud)