BobbyBorn2L8
BobbyBorn2L8

Reputation: 333

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?

Upvotes: 0

Views: 1180

Answers (1)

Lesiak
Lesiak

Reputation: 25936

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

Upvotes: 2

Related Questions