Skip to content

Instantly share code, notes, and snippets.

@amcsi
Created February 8, 2024 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcsi/55e092ad52b6db3916c985c3c431cf5e to your computer and use it in GitHub Desktop.
Save amcsi/55e092ad52b6db3916c985c3c431cf5e to your computer and use it in GitHub Desktop.
Response envelope
type ResponseEnvelopeYuki<T> = ResponseEnvelopeSuccess<T> | ResponseEnvelopeFailure;
type ResponseEnvelopeSuccess<T> = {
success: true;
} & T;
type ResponseEnvelopeFailure = {
success: false;
errorMessage: string;
};
async function myFetch<T>(userId: number): Promise<ResponseEnvelopeYuki<T>> {
try {
const responseBody = await ((await fetch('url')).json() as Promise<T>);
return {
...responseBody,
success: true,
};
} catch (e) {
// error handling.
throw e;
}
}
myFetch();
type MyCardItemResponse = ResponseEnvelopeYuki<{
items: string[];
}>;
async function addCartItem() {
return myFetch<MyCardItemResponse>(3434);
}
async function businessLogic() {
const result = await addCartItem();
if (result.success) {
console.info(result.items);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment