Search code examples
typescriptfetches6-promise

How should I declare a type for an Object being returned from a fetch call


I have a program here that is fetching information from the https://api.open5e.com/ I know the returned data will have the format

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

I have the following code here to fetch from the API

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

I am getting the error

Element implicitly has an 'any' type because expression of type '"count"' can't be used to index type 'Promise'.\n Property 'count' does not exist on type 'Promise'.", "source": "ts", "startLineNumber": 18, "startColumn": 61, "endLineNumber": 18, "endColumn": 74 }

I am fairly new to Typescript and don't really understand how I am meant to declare types for promises Have I declared this incorrectly or am I going about this the wrong way?


Solution

  • response.json() returns a Promise of the response body, not the body itself. You need to await for the result of response.json() to use it in further computations.

    Check the example:

    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))
    

    Playground