1.1.9 • Published 5 years ago

typescript-runtime-types v1.1.9

Weekly downloads
85
License
N/A
Repository
-
Last release
5 years ago

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'));
}
1.1.9

5 years ago

1.1.8

6 years ago

1.1.7

6 years ago

1.1.6

6 years ago

1.1.5

6 years ago

1.1.4

6 years ago

1.1.3

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago