Sibelius Seraphini Sibelius Seraphini - 3 years ago 194
Javascript Question

Is there an example of using fetch with flowjs?

I'm trying to use fetch in my async function, but flow is throwing this error

Error:(51, 26) Flow: Promise. This type is incompatible with union: type application of identifier

Promise
| type parameter
T
of await

this is a code that can generate this error:

async myfunc() {
const response = await fetch('example.com');
return await response.json();
}


I would like to type the response of
response.json

Answer Source

You may either annotate the return type of the function using Promise <T> where T is the desired type or assign the result to a temporary local with an explicit type annotation and then return that local. The function return type will then be inferred correctly.

Explicit return type annotation:

async myfunc(): Promise<{name: string}> {
    const response = await fetch('example.com');
    return await response.json();
}

Inferred return type from explicitly annotated local:

async myfunc() {
    const response = await fetch('example.com');
    const result: {name: string} = await response.json();
    return result;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download