DEV Community

Peter Leonov
Peter Leonov

Posted on

TypeScript type predicate generator

Hey folks! I've been working recently on several rather high load TypeScript projects that would consume a bunch of JSON API responses. No surprises I need to verify that the response data meets the definition in TypeScript to catch API regressions earlier. There are several solutions out there, but I want something simple and efficient specifically to fit the rising demand for high performance JS on mobile devices and in the various server runtimes.

Following the schema based code generation path other languages are using I've come up with a simple but effective type to code generator that takes a TS type and outputs a small readable function in strict TS that ensures a given unknown value satisfies the type. The produced code is JIT friendly and minifies really well.

As it is just a bunch of TS functions with no compiler magic involved any bundler, dev tool or TS aware runtime (like Deno, Bun and recently Node) can use it as is. Just import { isUser } from './type_predicates' and you're good to go.

Check out the playground and the repo. You can use it as a CLI tool or simply copy the generated code from the playground. Let me know what you think!

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay