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>;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.