Answer the question
In order to leave comments, you need to log in
How can I correctly write an asynchronous method on an object in typescript with a generic?
At the moment I have come to such a code, but knowing that in JS you can do it in different ways, 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))
}
Answer the question
In order to leave comments, you need to log in
What exactly do you want to reduce, it seems there is nowhere further: one type for input - one for output?
Well, you can remove async
and await
, 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 over Promise
and in this case does nothing, because fetch
it returns Promise
. this
.
In addition to Aetae - a generic is not needed here either
Yes, JSON parsing 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 plug it with our rightness?
Even if the data comes from our server, and we know exactly their type, they need to be checked, because there is no guarantee that no one made a mistake on the back, that we did not make a mistake in the description of the type we cast into.
Therefore, the type must be unknown so that TypeScript requires everything to be checked before use:
const ApiServiceModule = {
get: (url: string): Promise<unknown> => fetch(url)
.then(response => response.json())
.catch(err => console.error(err))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question