Generic API Response Envelope
Wrap API payloads in a generic envelope type carrying status, data, and optional error metadata so clients get full inference from a single shape.
Code
export interface ApiSuccess<T> {
status: "success";
data: T;
requestId: string;
}
export interface ApiFailure {
status: "error";
code: string;
message: string;
requestId: string;
}
export type ApiResponse<T> = ApiSuccess<T> | ApiFailure;
export function isSuccess<T>(response: ApiResponse<T>): response is ApiSuccess<T> {
return response.status === "success";
}
export async function request<T>(url: string): Promise<ApiResponse<T>> {
const raw = await fetch(url);
return (await raw.json()) as ApiResponse<T>;
}How the snippet works
One way to read it: the functions isSuccess and request, doing all the work.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- This is browser-side code —
fetchwill not resolve in Node.
Applying it
isSuccess is the public entry point; everything else in the file exists to support it.
Statements that matter
return (await raw.json()) as ApiResponse<T>;
return response.status === "success";
const raw = await fetch(url);
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `isSuccess`, `request` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.