Untypeable

Get type-safe access to any API, with a zero-bundle size option.

README

Untypeable


Get type-safe access to any API, with a zero-bundle size option.

The Problem


If you're lucky enough to use tRPC , GraphQL , or OpenAPI , you'll be able to get type-safe access to your API- either through a type-safe RPC or codegen.

But what about the rest of us?

What do you do if your API has no types?

Solution


Enter untypeable- a first-class library for typing API's you don't control.

🚀 Get autocomplete on your entire API*, without needing to set up a single generic function.
💪 Simple to configure, and extremely flexible*.
🤯* Choose between two modes:
Zero bundle-size: use import typeto ensure untypeableadds nothing to your bundle.
Strong types: integrates with libraries like Zod to add runtime safety to the types.

Keep things organized*with helpers for merging and combining your config.
❤️ You bring the fetcher, we bring the types. There's no hidden magic*.

Quickstart


npm i untypeable

  1. ``` ts
  2. import { initUntypeable, createTypeLevelClient } from "untypeable";

  3. // Initialize untypeable
  4. const u = initUntypeable();

  5. type User = {
  6.   id: string;
  7.   name: string;
  8. };

  9. // Create a router
  10. // - Add typed inputs and outputs
  11. const router = u.router({
  12.   "/user": u.input<{ id: string }>().output<User>(),
  13. });

  14. const BASE_PATH = "http://localhost:3000";

  15. // Create your client
  16. // - Pass any fetch implementation here
  17. const client = createTypeLevelClient<typeof router>((path, input) => {
  18.   return fetch(BASE_PATH + path + `?${new URLSearchParams(input)}`).then(
  19.     (res) => res.json(),
  20.   );
  21. });

  22. // Type-safe data access!
  23. // - user is typed as User
  24. // - { id: string } must be passed as the input
  25. const user = await client("/user", {
  26.   id: "1",
  27. });
  28. ```

SWAPI Example


We've added a full example of typing swapi.dev.

Zero-bundle mode


You can set up untypeableto run in zero-bundle mode. This is great for situations where you trust the API you're calling, but it just doesn't have types.

To set up zero-bundle mode, you'll need to:

Define your router in a file called router.ts.
Export the type of your router: export type MyRouter = typeof router;

  1. ``` ts
  2. // router.ts

  3. import { initUntypeable } from "untypeable";

  4. const u = initUntypeable();

  5. type User = {
  6.   id: string;
  7.   name: string;
  8. };

  9. const router = u.router({
  10.   "/user": u.input<{ id: string }>().output<User>(),
  11. });

  12. export type MyRouter = typeof router;
  13. ```

In a file called client.ts, import createTypeLevelClientfrom untypeable/type-level-client.

  1. ``` ts
  2. // client.ts

  3. import { createTypeLevelClient } from "untypeable/client";
  4. import type { MyRouter } from "./router";

  5. export const client = createTypeLevelClient<MyRouter>(() => {
  6.   // your implementation...
  7. });
  8. ```

How does this work?


This works because createTypeLevelClientis just an identity function, which directly returns the function you pass it. Most modern bundlers are smart enough to collapse identity functions and erase type imports, so you end up with:

  1. ``` ts
  2. // client.ts

  3. export const client = () => {
  4.   // your implementation...
  5. };
  6. ```

Runtime-safe mode


Sometimes, you just don't trust the API you're calling. In those situations, you'll often like to validatethe data you get back.

untypeableoffers first-class integration with Zod . You can pass a Zod schema to u.inputand u.outputto ensure that these values are validated with Zod.

  1. ``` ts
  2. import { initUntypeable, createSafeClient } from "untypeable";
  3. import { z } from "zod";

  4. const u = initUntypeable();

  5. const router = u.router({
  6.   "/user": u
  7.     .input(
  8.       z.object({
  9.         id: z.string(),
  10.       }),
  11.     )
  12.     .output(
  13.       z.object({
  14.         id: z.string(),
  15.         name: z.string(),
  16.       }),
  17.     ),
  18. });

  19. export const client = createSafeClient(router, () => {
  20.   // Implementation...
  21. });
  22. ```

Now, every call made to client will have its inputand outputverified by the zod schemas passed.

Configuration & Arguments


untypeablelets you be extremely flexible with the shape of your router.

Each level of the router corresponds to an argument that'll be passed to your client.

  1. ``` ts
  2. // A router that looks like this:
  3. const router = u.router({
  4.   github: {
  5.     "/repos": {
  6.       GET: u.output<string[]>(),
  7.       POST: u.output<string[]>(),
  8.     },
  9.   },
  10. });

  11. const client = createTypeLevelClient<typeof router>(() => {});

  12. // Will need to be called like this:
  13. client("github", "/repos", "POST");
  14. ```

You can set up this argument structure using the methods below:

.pushArg


Using the .pushArgmethod when we initUntypeablelets us add new arguments that must be passed to our client.

  1. ``` ts
  2. import { initUntypeable, createTypeLevelClient } from "untypeable";

  3. // use .pushArg to add a new argument to
  4. // the router definition
  5. const u = initUntypeable().pushArg<"GET" | "POST" | "PUT" | "DELETE">();

  6. type User = {
  7.   id: string;
  8.   name: string;
  9. };

  10. // You can now optionally specify the
  11. // method on each route's definition
  12. const router = u.router({
  13.   "/user": {
  14.     GET: u.input<{ id: string }>().output<User>(),
  15.     POST: u.input<{ name: string }>().output<User>(),
  16.     DELETE: u.input<{ id: string }>().output<void>(),
  17.   },
  18. });

  19. // The client now takes a new argument - method, which
  20. // is typed as 'GET' | 'POST' | 'PUT' | 'DELETE'
  21. const client = createTypeLevelClient<typeof router>((path, method, input) => {
  22.   let resolvedPath = path;
  23.   let resolvedInit: RequestInit = {};

  24.   switch (method) {
  25.     case "GET":
  26.       resolvedPath += `?${new URLSearchParams(input as any)}`;
  27.       break;
  28.     case "DELETE":
  29.     case "POST":
  30.     case "PUT":
  31.       resolvedInit = {
  32.         method,
  33.         body: JSON.stringify(input),
  34.       };
  35.   }

  36.   return fetch(resolvedPath, resolvedInit).then((res) => res.json());
  37. });

  38. // This now needs to be passed to client, and
  39. // is still beautifully type-safe!
  40. const result = await client("/user", "POST", {
  41.   name: "Matt",
  42. });
  43. ```

You can call this as many times as you want!

  1. ``` ts
  2. const u = initUntypeable()
  3.   .pushArg<"GET" | "POST" | "PUT" | "DELETE">()
  4.   .pushArg<"foo" | "bar">();

  5. const router = u.router({
  6.   "/": {
  7.     GET: {
  8.       foo: u.output<string>,
  9.     },
  10.   },
  11. });
  12. ```

.unshiftArg


You can also add an argument at the startusing .unshiftArg. This is useful for when you want to add different base endpoints:

  1. ``` ts
  2. const u = initUntypeable().unshiftArg<"github", "youtube">();

  3. const router = u.router({
  4.   github: {
  5.     "/repos": u.output<{ repos: { id: string }[] }>(),
  6.   },
  7. });
  8. ```

.args


Useful for when you want to set the args up manually:

  1. ``` ts
  2. const u = initUntypeable().args<string, string, string>();

  3. const router = u.router({
  4.   "any-string": {
  5.     "any-other-string": {
  6.       "yet-another-string": u.output<string>(),
  7.     },
  8.   },
  9. });
  10. ```

Organizing your routers


.add


You can add more detail to a router, or split it over multiple calls, by using router.add.

  1. ``` ts
  2. const router = u
  3.   .router({
  4.     "/": u.output<string>(),
  5.   })
  6.   .add({
  7.     "/user": u.output<User>(),
  8.   });
  9. ```

.merge


You can merge two routers together using router.merge. This is useful for when you want to combine multiple routers (perhaps in different modules) together.

  1. ``` ts
  2. import { userRouter } from "./userRouter";
  3. import { postRouter } from "./postRouter";

  4. export const baseRouter = userRouter.merge(postRouter);
  5. ```