1.3.0 • Published 3 years ago

@grabvintage/ts-schemaof v1.3.0

Weekly downloads
14
License
MIT
Repository
github
Last release
3 years ago

ts-schemaof

Get a JSON schema of your TypeScript interface at compile time.

$ npm install @grabvintage/ts-schemaof --save-dev

Setup

TypeScript

You need to use ttsc or any other TypeScript compiler that supports plugins. Once you have that, add a new plugin definition to your tsconfig.json:

{
  "compilerOptions": {
    ...
    "plugins": [{ "transform": "@grabvintage/ts-schemaof" }]
  }
}

Webpack

You need to use ts-loader and supply it with a custom before transformer:

const TsSchemaofTransformer = require('@grabvintage/ts-schemaof').default;

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          'babel-loader',
          {
            loader: 'ts-loader',
            options: {
              getCustomTransformers: (program) => ({
                before: [TsSchemaofTransformer(program)],
              }),
            },
          },
        ],
        exclude: /node_modules/,
      },
    ],
  },
};

Usage

import Ajv from 'ajv';

type FooBar = {
  foo: string;
  bar: string;
};

const ajv = new Ajv({ removeAdditional: 'all' });
const validate = ajv.compile(schemaof<FooBar>());

validate({ foo: 'foo', bar: 'bar' }); // passes!