How can you correctly write an asynchronous method on an object in typescript with a generic?
-
At the moment I have come to such code, but knowing that there are different ways in JS, maybe there are other ways. Perhaps more compact and expressive?
const ApiServiceModule = { get: async <T>(url: string): Promise<T> => await fetch(url) .then(response => response.json()) .catch(err => console.error(err)) }
JavaScript Anonymous, Jul 30, 2019 -
What exactly do you want to shorten, it seems like there is nowhere to go: one type at the entrance - one at the exit?
Well, you can removeasync
andawait
, they are not needed here:
const ApiServiceModule = {
get: <T>(url: string): Promise<T> => fetch(url)
.then(response => response.json())
.catch(err => console.error(err))
}async
/await
is just sugar overPromise
and in this case they do nothing, becausefetch
already returnsPromise
.
P.S. Well, I wouldn't call it a method, it's a property with a function. The method has access tothis
.Anonymous -
In addition to Aetae - generic is not needed here either
Yes, parsing JSON returns any (for historical reasons) and it can be easily cast into any type with such a generic. But why use TypeScript at all if we always shut it up with our righteousness?
Even if the data comes from our server, and we know their type for sure, they need to be checked, because there is no guarantee that no one was mistaken on the back, that we were not mistaken in the description of the type we are casting.
Therefore, the type must be unknown for TypeScript to require checking everything before use:const ApiServiceModule = {
get: (url: string): Promise<unknown> => fetch(url)
.then(response => response.json())
.catch(err => console.error(err))
}Anonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!