Dev Helpers
← Back

Encode a typed query object

Encode a typed query object 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(
  ((q: { page: number; tag: string }) =>
    new URLSearchParams({ page: String(q.page), tag: q.tag }).toString())({
    page: 2,
    tag: "web apps",
  }),
);

Sample output

page=2&tag=web+apps