首页 > 解决方案 > 我应该如何声明从 fetch 调用返回的 Object 的类型

问题描述

我这里有一个程序从https://api.open5e.com/获取信息 我知道返回的数据将具有格式

type ResponseFormat = {
"count": number,
"next": string | null,
"previous": string | null,
"results": Object[]
}

我在这里有以下代码可以从 API 中获取

async getFromApi(){
    let response = await fetch(this.sourcePath);
    let json: Promise<ResponseFormat> = response.json();
        
    response = await fetch(`${this.sourcePath}/?limit=${json["count"]}`)
}

我收到错误

元素隐式具有 'any' 类型,因为类型 '"count"' 的表达式不能用于索引类型 'Promise'。\n 类型 'Promise' 上不存在属性 'count'。", "source": “ts”,“startLineNumber”:18,“startColumn”:61,“endLineNumber”:18,“endColumn”:74 }

我对 Typescript 还很陌生,我真的不明白我是如何为 Promise 声明类型的我是错误地声明了这一点,还是我以错误的方式处理了这个?

标签: typescriptfetches6-promise

解决方案


response.json()返回响应主体的 Promise,而不是主体本身。您需要等待结果response.json()才能在进一步的计算中使用它。

检查示例:

type ResponseFormat = {
"count": number,
"next": string | null,
"previous": string | null,
"results": Object[]
}

const sourcePath = 'https://api.open5e.com/spells';

async function getFromApi(): Promise<ResponseFormat> {
    const responsePage1 = await fetch(sourcePath);
    const jsonPage1: ResponseFormat = await responsePage1.json();
        
    const response = await fetch(`${sourcePath}/?limit=${jsonPage1.count}`)
    const json: ResponseFormat = await response.json();
    return json;
}

getFromApi().then(r => console.log(r.count))

操场


推荐阅读