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!

Top comments (0)