Trouble with telling typescript the return type of fetch when using @sapphire/result
Hi there,
I have a function that fetches an API using the native
fetch function. The fetch is wrapped in Result.fromAsync(), and I wanted to do Result.fromAsync<Promise<APIResponse>> since I know what the API will return. The problem is, when doing Result.fromAsync<Promise<APIResponse>> Typescript says that Response is missing certain properties that I know the API will return.
How would I tell Typescript I know that the fetch will return this?
6 Replies
Should I have put this in #Coding since it's more TS related and not sapphire related
@nettech try this:
Assuming
fetch is whatwg-spec compliantyep that works
my original solution did a straight return
because i wanted to avoid defining variables
that i was gonna use immediately
The problem is you have to send the request and parse it as json. Both are two different promises, and both can reject, but I assumed you wanted to handle them as one. So it would need to be in a callback.
Also, you have a few type confusions
oh, which ones?
also thanks for the quick reply
The most important one is, as I said,
fetch doesn't return json.
Also, the value in the generics should not be a promise, it should be the resolved value.