YousefED / typescript-json-schema

Generate json-schema from your Typescript sources
BSD 3-Clause "New" or "Revised" License
3.14k stars 323 forks source link

Type Intersection fail but Extending Interface works #359

Open puppybits opened 4 years ago

puppybits commented 4 years ago

We're composing types to make partial validation. Both generate schemas but Type Intersection schemas fail in AJV but extending an Interface is accepted by AJV as a valid Schema.

interface MyId {
  id: string;
}
interface MyName {
  name: string;
}

// generates schema but fails in AJV
export type FailedSchema = Pick<MyId, 'id'> & Pick<MyName, 'name'>;

// generates schema which passes AJV
export interface ValidSchema extends Pick<MyId, 'id'>, Pick<MyName, 'name'>

Type Intersections create an allOf at the root which fail when sending to AJV.

FailedSchema { allOf:
         [ { '$ref': '#/definitions/Pick<MyId,\"id\">' },
           { '$ref': '#/definitions/Pick<MyName,\"name\">' } ],
        definitions:
         { 'Pick<MyId,\"id\">': { type: 'object', properties: [Object], required: [Array] },
           'Pick<MyName,\"name\">': { type: 'object', properties: [Object], required: [Array] } },
        '$schema': 'http://json-schema.org/draft-07/schema#' }

ValidSchema { type: 'object',
        properties:
         { id: { minLength: 20, type: 'string' },
           name: { minLength: 2, type: 'string' } },
        required: [ 'id', 'name' ],
        '$schema': 'http://json-schema.org/draft-07/schema#' }

AJV error:

{"message": "schema is invalid: data.allOf[0].$ref should match format \"uri-reference\", data.allOf[1].$ref should match format \"uri-reference\"", "name": "Error", "stack": "Error: schema is invalid: data.allOf[0].$ref should match format \"uri-reference\", data.allOf[1].$ref should match format \"uri-reference\"
        at Ajv.validateSchema (/Users/bobby/code/tara-js/node_modules/ajv/lib/ajv.js:178:16)
        at Ajv._addSchema (/Users/bobby/code/tara-js/node_modules/ajv/lib/ajv.js:307:10)
water-a commented 3 years ago

@puppybits It seems to fail because the URI should not include "<" and ">". I've resolved this by forking and removing those characters. I assume this would work too if you just used the flag "uniqueNames".

domoritz commented 3 years ago

I fixed this issue in https://github.com/vega/ts-json-schema-generator.