'Type the result of Promisse
Is possible to avoid this cast:
(await getCryptocurrencyMap(1, 5)) as Cryptocurrency[]
And return the type on getCryptocurrencyMap?
Full code:
type Cryptocurrency = {
id: number
symbol: string
name: string
}
const getCryptocurrencyMap = (start: number, limit: number) =>
new Promise(async (resolve, reject) => {
try {
const response = await axios.get(`${BASE_URL}/v1/cryptocurrency/map`, {
params: { start, limit },
headers: {
'X-CMC_PRO_API_KEY': COINMARKETCAP_APIKEY,
},
})
resolve(response.data.data)
} catch (error) {
reject(error)
}
})
export const getCryptocurrencies = async () => {
const arr = (await getCryptocurrencyMap(1, 5)) as Cryptocurrency[]
return arr.map(({symbol, name}) => ({ [symbol]: name }))
}
Solution 1:[1]
Yes -- use generics:
new Promise<Cryptocurrency[]>((resolve, reject) => {
// resolve can only be used with `Cryptocurrency[]` now
});
However, the new Promise wrapper seems redundant here. Just return the axios response, which also allows for generics:
const result = await axios.get<Cryptocurrency[]>(url, opts);
const currencies = result.currencies; // data is Cryptocurrency[]
Note that this is pure Typescript runtime casting. It'll not guarantee you that the actually returned result of the API is of the specified type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
