Skip to content

Instantly share code, notes, and snippets.

@gabrielmlinassi
Last active October 13, 2022 13:11
Show Gist options
  • Save gabrielmlinassi/8b69291906567f5a09dcec60c97b8218 to your computer and use it in GitHub Desktop.
Save gabrielmlinassi/8b69291906567f5a09dcec60c97b8218 to your computer and use it in GitHub Desktop.
Handle error with TypeScript
interface Pokemon {
id: number;
name: string;
height: number;
types: { id: number; name: string }[];
}
type GetPokemonSuccessResult = { isOk: true; data: Pokemon; error: null };
type GetPokemonErrorResult = { isOk: false; data: null; error: string };
type GetPokemonResult = GetPokemonSuccessResult | GetPokemonErrorResult;
function getPokemon(): GetPokemonResult {
if (Math.random() > 0.5) {
return {
isOk: true,
data: {
id: 1,
name: "pokemon 1",
height: 137,
types: [{ id: 1, name: "type 1" }],
},
error: null,
};
} else {
return {
isOk: false,
data: null,
error: "Some error happened",
};
}
}
function handleApiCall() {
const { isOk, data, error } = getPokemon();
if (isOk) {
console.log(data);
} else {
console.log(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment