Last active
October 12, 2022 03:18
-
-
Save DonHuskini/817057d0ad72ea0fcdc34d591cd59875 to your computer and use it in GitHub Desktop.
How to type Async service function response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for sake of simplicity, I'm adding all things in this file but | |
// I recommend spliting them into their respective files as suggested | |
const url = 'https://pokeapi.co/api/v2' | |
const getIdFromUrl = (url: string) => { | |
const splitted = url.split("/"); | |
const id = +splitted[splitted.length - 2]; | |
return id; | |
}; | |
interface PokemonDetailsDTO { | |
... // used to type your API response | |
} | |
// used to type the interface used on your app | |
export interface PokemonDetails { | |
id: number; | |
name: string; | |
height: number; | |
types: { | |
id: number; | |
name: string; | |
}[]; | |
} | |
type GetPokemonDetailsSuccessResponse = { | |
isOk: true; | |
data: PokemonDetails; | |
error: null; | |
}; | |
type GetPokemonDetailsErrorResponse = { | |
isOk: false; | |
data: null; | |
error: string; | |
}; | |
type GetPokemonDetailsResponse = | |
| GetPokemonDetailsSuccessResponse | |
| GetPokemonDetailsErrorResponse; | |
export const getPokemonDetails = async ( | |
id: number | |
): Promise<GetPokemonDetailsResponse> => { | |
try { | |
const resp = await fetch(`${url}/${id}`); | |
const data: PokemonDetailsDTO = await resp.json(); | |
// transform data | |
const transformedData: PokemonDetails = { | |
id: data.id, | |
name: data.name, | |
height: data.height, | |
types: data.types.map((type) => ({ | |
id: getIdFromUrl(type.type.url), | |
name: type.type.name, | |
})), | |
}; | |
return { | |
isOk: true, | |
data: transformedData, | |
error: null, | |
}; | |
} catch (e) { | |
return { | |
isOk: false, | |
data: null, | |
error: (e as Error).message, | |
}; | |
} | |
}; | |
// Usage: | |
const { isOk, data, error } = await getPokemonDetails(id) | |
if (isOk) console.log(data) // type: data=PokemonDetails, error=null | |
else console.log(error) // type: data=null, error=string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment