Dev Helpers
← Back

Represent a validated response union

Represent a validated response union using TypeScript.

Open this example in the interactive library

Source code

type Route = { path: string; method: "GET" | "POST" };
const routes = {
  list: { path: "/jobs", method: "GET" },
  create: { path: "/jobs", method: "POST" },
} as const satisfies Record<string, Route>;
console.log(
  ((
    ok: boolean,
  ): { status: 200; data: string[] } | { status: 404; error: string } =>
    ok ? { status: 200, data: ["api"] } : { status: 404, error: "Missing" })(
    true,
  ),
);

Sample output

{ status: 200, data: [ 'api' ] }