Search code examples
javascriptnode.jstypescripttypescript2.2

Use TypeScript interface for runtime validation in/of JS code


I can create a TypeScript interface like so which will help with static typing:

interface IFoo {
   bar: string,
   baz: boolean
}

but I am wondering if there is a way to convert this information to JS and use it to do runtime validation as well? Otherwise I'd likely have to keep track of this info in two different places which is no fun.

Anyone know if this is possible somehow?

What it might look like is

const ifoo = {
     bar: 'String',
     baz: 'Boolean'
}

and then I could use an object like that to do runtime validation.


Solution

  • Yes! The module ts-interface-builder automatically converts interfaces defined in a TypeScript file into descriptors similar to what you suggest, namely:

    import * as t from "ts-interface-checker";
    export const IFoo = t.iface([], {
      "bar": "string",
      "baz": "boolean",
    });
    

    It works in conjunction with ts-interface-checker (distributed as a separate npm module) which uses these descriptors to do runtime validation with informative error messages.