mafintosh / is-my-json-valid

A JSONSchema validator that uses code generation to be extremely fast
MIT License
965 stars 111 forks source link

TypeScript: passing schema via variable doesn't work #173

Open bsnote opened 6 years ago

bsnote commented 6 years ago

TypeScript fails to compile the following snippet:

import createValidator = require('is-my-json-valid');

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' },
  },
  required: [
    'name'
  ]
};

createValidator(schema);

showing the following error:

[ts]
Argument of type '{ type: string; properties: { name: { type: string; }; age: { type: string; }; }; required: string[]; }' is not assignable to parameter of type 'AnySchema'.
  Type '{ type: string; properties: { name: { type: string; }; age: { type: string; }; }; required: string[]; }' is not assignable to type 'AnyOneOfSchema'.
    Property 'oneOf' is missing in type '{ type: string; properties: { name: { type: string; }; age: { type: string; }; }; required: string[]; }'.
LinusU commented 6 years ago

Yeah, I wrote down some thoughts about that here: https://github.com/mafintosh/is-my-json-valid/pull/170#issuecomment-412480162

Unfortunately, this is not something that we can support right now, because of limitations in TypeScript. You can work around it by explicitly narrowing your types:

import createValidator = require('is-my-json-valid');

const schema = {
  type: 'object' as 'object',
  properties: {
    name: { type: 'string' as 'string' },
    age: { type: 'number' as 'number' },
  },
  required: [
    'name' as 'name'
  ]
};

createValidator(schema);

Feel free to contribute to the discussion here on how to best solve this in TypeScript: https://github.com/Microsoft/TypeScript/issues/26332