npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

typescript-runtime-types

v1.1.9

Published

Typescript transformer allowing to test if the structure of an object matches an interface/type

Readme

Typescript Runtime Types

What is this ?

We all know data in Javascript is very flexible, which sometimes makes it unreliable. Typescript takes the first step and makes sure all the data in your project is consistent with your declared types. However, sometimes you receive data from an unknown source: it could be data received from a client on a node server or just data from a third party Library/API. Your choice here is to either trust this source or write tedious checks on the type and value of each members. Granted, this has been facilitated by great libraries like ajv or io-ts, but using these libraries requires boiler plater code or forces you to adapt your project's coding style.

Introducting Runtime Types

The idea is simple, you define your types as you would always do in Typescript and the Typescript Runtime Types compiler plugin will at compile time generate the code that checks the structure and content of your data.

Let's take an example. Say you are writing a nodejs server in Typescript and expect to receive this user type from the client when the register api endpoint is called.

interface User{
    id: number
    name: string
    email: string
    password: string
}

Since you should never trust user input, you need to verify if the data has the right structure. This is done very simply with runtime types:

let isValid: boolean = checkObjectStructure<User>(receivedUser)

The above code will be transformed during the compilation by the following:

let isValid = function (__name__) {
    if (!(typeof __name__.id === typeof 1))
        return false;
    if (!(typeof __name__.name === typeof ""))
        return false;
    if (!(typeof __name__.email === typeof ""))
        return false;
    if (!(typeof __name__.password === typeof ""))
        return false;
    return true;
}(receivedUser);

As you can see it generated the code necessary to check the object structure just from the interface declaration.

Most of the time you also need to validate the content of the data in addition to the structure. This is possible using JSDoc style comments on each member in the interface declaration. Let's change the interface declaration of our example to:

interface User{
    /** @minOrEqual 0 */
    id: number
    /** 
     * @maxLength 24
     * @minLength 1
     */
    name: string
    /** 
     * @isEmail
     */
    email: string
    /** 
     * check the strength of the password
     * @match /^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})/g
     */
    password: string
}

The compiled output changes to:

//TODO

TODO setup example folder

How to use the custom transformer

Unfortunately, TypeScript itself does not currently provide any easy way to use custom transformers (See https://github.com/Microsoft/TypeScript/issues/14419). The followings are the example usage of the custom transformer.

This section has been kindly stolen from the great explanations provided by this repo: https://github.com/kimamula/ts-transformer-keys

webpack (with awesome-typescript-loader)

See examples/webpack for detail.

// webpack.config.js
const transformer = require('typescript-runtime-types/transformer').default;

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        options: {
          getCustomTransformers: program => ({
              before: [
                  transformer(program)
              ]
          })
        }
      }
    ]
  }
};

Rollup (with rollup-plugin-typescript2)

See examples/rollup for detail.

// rollup.config.js
import typescript from 'rollup-plugin-typescript2';
import transformer from 'typescript-runtime-types/transformer';

export default {
  // ...
  plugins: [
    typescript({ transformers: [service => ({
      before: [ transformer(service.getProgram()) ],
      after: []
    })] })
  ]
};

ttypescript

See examples/ttypescript for detail. See ttypescript's README for how to use this with module bundlers such as webpack or Rollup.

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "plugins": [
      { "transform": "typescript-runtime-types/transformer" }
    ]
  },
  // ...
}

TypeScript API

See test for detail. You can try it with $ npm test.

const ts = require('typescript');
const transformer = require('typescript-runtime-types/transformer').default;

const program = ts.createProgram([/* your files to compile */], {
  strict: true,
  noEmitOnError: true,
  target: ts.ScriptTarget.ES5
});

const transformers = {
  before: [transformer(program)],
  after: []
};
const { emitSkipped, diagnostics } = program.emit(undefined, undefined, undefined, false, transformers);

if (emitSkipped) {
  throw new Error(diagnostics.map(diagnostic => diagnostic.messageText).join('\n'));
}