Using the Result type in TypeScript

let response;
try {
response = await myApiCall();
} catch(e) {
}// use response down here
try {
const response = await myApiCall();
// insert a bunch of code here for 20+ lines (or whatever)
} catch(e) {
}
type Result<Ok,Err> = { result: 'ok', data: Ok } | { result: 'err', data: Err }
interface ApiData {
foo: string
}
const myApiCall = async (): Promise<Result<ApiData, string>> => {
// try block now lives here
try {
const res = await fetch('api.com')
const jsonData = await res.json()
if (!jsonData) {
return { result: 'err', data: 'No data found' }
}
return { result: 'ok', data: jsonData }
} catch(e) {
return { result: 'err', data: 'Something unexpected happened!' }
}
const { result, data }= await myApiCall();
if (result === 'error') {
// handle error here
// return to halt function
return;
}
// use data to represent as needed

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rob Bertram

Rob Bertram

“A language that doesn’t affect the way you think about programming is not worth knowing.”