Get a JSON schema of your TypeScript interface at compile time.
$ npm install @grabvintage/ts-schemaof --save-dev
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" }]
}
}
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/,
},
],
},
};
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!