ajv icon indicating copy to clipboard operation
ajv copied to clipboard

Create two JSONSchemaType from two interfaces in Typescript where one extends from the other

Open aLosada7 opened this issue 4 years ago • 1 comments

I'm using Ajv with Typescript and I'd like to create a JSONSchemaType from another. I have two interfaces (one of them extends from another) and I would like to do somethig similar with Ajv for form validation. I don't know if this is possible or I do have to replicate the code.

Here is an example:

export interface IAddressBookBase {
  id?: number;
  address: string;
  clientReference: string;
}

export interface IAddressBook extends IAddressBookBase {
  name: string;
}

And their schemas:

export const addressBookBaseSchema: JSONSchemaType<IAddressBookBase> = {
  type: 'object',
  properties: {
    id: { type: 'integer', nullable: true },
    address: { type: 'string' },
    clientReference: { type: 'string' },
  },
  required: ['clientReference'],
};

export const addressBookSchema: JSONSchemaType<IAddressBook> = {
  type: 'object',
  properties: {
    name: { type: 'string' },
  },
  required: ['name'],
};

I tried using spread operator and looked for help on the Internet but I wasn't lucky. Some help would be appreciated.

aLosada7 avatar Dec 09 '21 15:12 aLosada7

Disclaimer: I'm not a maintainer of this library but I've used it quite a bit and I'm familiar with the type definitions. That said, my two cents is that spreading won't work because JSONSchemaType<IAddressBookBase> ['properties'] is an optional property. You'll have to duplicate code in this case. I'd be happy to be proved wrong but from what I can see, this isn't possible.

stuft2 avatar Jan 27 '22 21:01 stuft2

any update about typescript extennds?

frankie-zeng avatar Jan 07 '23 02:01 frankie-zeng