Skip to content

Repository files navigation

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 type to ensure untypeable adds 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

import{initUntypeable,createTypeLevelClient}from"untypeable";// Initialize untypeableconstu=initUntypeable();typeUser={id: string;name: string;};// Create a router// - Add typed inputs and outputsconstrouter=u.router({"/user": u.input<{id: string}>().output<User>(),});constBASE_PATH="http://localhost:3000";// Create your client// - Pass any fetch implementation hereconstclient=createTypeLevelClient<typeofrouter>((path,input)=>{returnfetch(BASE_PATH+path+`?${newURLSearchParams(input)}`).then((res)=>res.json(),);});// Type-safe data access!// - user is typed as User// - { id: string } must be passed as the inputconstuser=awaitclient("/user",{id: "1",});

SWAPI Example

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

Zero-bundle mode

You can set up untypeable to 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:

  1. Define your router in a file called router.ts.
  2. Export the type of your router: export type MyRouter = typeof router;
// router.tsimport{initUntypeable}from"untypeable";constu=initUntypeable();typeUser={id: string;name: string;};constrouter=u.router({"/user": u.input<{id: string}>().output<User>(),});exporttypeMyRouter=typeofrouter;
  1. In a file called client.ts, import createTypeLevelClient from untypeable/type-level-client.
// client.tsimport{createTypeLevelClient}from"untypeable/client";importtype{MyRouter}from"./router";exportconstclient=createTypeLevelClient<MyRouter>(()=>{// your implementation...});

How does this work?

This works because createTypeLevelClient is 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:

// client.tsexportconstclient=()=>{// your implementation...};

Runtime-safe mode

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

untypeable offers first-class integration with Zod. You can pass a Zod schema to u.input and u.output to ensure that these values are validated with Zod.

import{initUntypeable,createSafeClient}from"untypeable";import{z}from"zod";constu=initUntypeable();constrouter=u.router({"/user": u.input(z.object({id: z.string(),}),).output(z.object({id: z.string(),name: z.string(),}),),});exportconstclient=createSafeClient(router,()=>{// Implementation...});

Now, every call made to client will have its input and output verified by the zod schemas passed.

Configuration & Arguments

untypeable lets 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.

// A router that looks like this:constrouter=u.router({github: {"/repos": {GET: u.output<string[]>(),POST: u.output<string[]>(),},},});constclient=createTypeLevelClient<typeofrouter>(()=>{});// Will need to be called like this:client("github","/repos","POST");

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

.pushArg

Using the .pushArg method when we initUntypeable lets us add new arguments that must be passed to our client.

import{initUntypeable,createTypeLevelClient}from"untypeable";// use .pushArg to add a new argument to// the router definitionconstu=initUntypeable().pushArg<"GET"|"POST"|"PUT"|"DELETE">();typeUser={id: string;name: string;};// You can now optionally specify the// method on each route's definitionconstrouter=u.router({"/user": {GET: u.input<{id: string}>().output<User>(),POST: u.input<{name: string}>().output<User>(),DELETE: u.input<{id: string}>().output<void>(),},});// The client now takes a new argument - method, which// is typed as 'GET' | 'POST' | 'PUT' | 'DELETE'constclient=createTypeLevelClient<typeofrouter>((path,method,input)=>{letresolvedPath=path;letresolvedInit: RequestInit={};switch(method){case"GET":
resolvedPath+=`?${newURLSearchParams(inputasany)}`;break;case"DELETE":
case"POST":
case"PUT":
resolvedInit={
method,body: JSON.stringify(input),};}returnfetch(resolvedPath,resolvedInit).then((res)=>res.json());});// This now needs to be passed to client, and// is still beautifully type-safe!constresult=awaitclient("/user","POST",{name: "Matt",});

You can call this as many times as you want!

constu=initUntypeable().pushArg<"GET"|"POST"|"PUT"|"DELETE">().pushArg<"foo"|"bar">();constrouter=u.router({"/": {GET: {foo: u.output<string>,},},});

.unshiftArg

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

constu=initUntypeable().unshiftArg<"github","youtube">();constrouter=u.router({github: {"/repos": u.output<{repos: {id: string}[]}>(),},});

.args

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

constu=initUntypeable().args<string,string,string>();constrouter=u.router({"any-string": {"any-other-string": {"yet-another-string": u.output<string>(),},},});

Organizing your routers

.add

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

constrouter=u.router({"/": u.output<string>(),}).add({"/user": u.output<User>(),});

.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.

import{userRouter}from"./userRouter";import{postRouter}from"./postRouter";exportconstbaseRouter=userRouter.merge(postRouter);

About

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

Resources

Stars

383 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages