Y
Y
YI2020-10-04 23:34:44
JavaScript
YI, 2020-10-04 23:34:44

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

2 answer(s)
A
Aetae, 2020-10-04
@AngryBot

What exactly do you want to reduce, it seems there is nowhere further: one type for input - one for output?
Well, you can remove asyncand 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/ awaitis just sugar over Promiseand in this case does nothing, because fetchit returns Promise.
PS Well, I wouldn't call it a method, it's a property with a function. The method has access to this.

D
Dmitry Belyaev, 2020-10-05
@bingo347

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 question

Ask a Question

731 491 924 answers to any question