Last active
October 13, 2022 13:11
-
-
Save DonHuskini/8b69291906567f5a09dcec60c97b8218 to your computer and use it in GitHub Desktop.
Handle error with TypeScript
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
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