vitalics / ajv-ts

First-class ajv typescript JSON-schema builder inspired from Zod
https://www.npmjs.com/package/ajv-ts
MIT License
43 stars 3 forks source link

Merge is not like for like with Zod #57

Closed thoroc closed 2 months ago

thoroc commented 3 months ago

Describe the bug I was just trying this as an alternative to Zod, but the merge schema method isn't working in like for like fashion. Am I missing something?

To Reproduce Clone the repo at https://github.com/thoroc/zod-is-dead

Expected behavior All test passess

Desktop (please complete the following information):

Additional context I have put some log output to see what's the object on the Ajv truck in the example and this is what I get:

Vehicle Schema

export const AjvVehicleSchema = s.object({
  make: s.string(),
  model: s.string(),
  year: s.number(),
});

export type AjvVehicle = s.infer<typeof AjvVehicleSchema>;

Truck Schema

export const AjvTruckSchema = s
  .object({
    commercialCapacity: s.number(),
    forwardCabin: s.boolean(),
    wheels: s.number(),
  })
  .merge(AjvVehicleSchema);

export type AjvTruck = s.infer<typeof AjvTruckSchema>;

Truck instance

{
  make: 'Bugatti',
  model: 'Model T',
  year: 2020,
  commercialCapacity: 1000,
  forwardCabin: true,
  wheels: 4
}

AjvTruckSchema.schema

{
  type: 'object',
  properties: {
    commercialCapacity: { type: 'number' },
    forwardCabin: { type: 'boolean' },
    wheels: { type: 'number' },
    type: undefined,
    properties: undefined
  }
}
thoroc commented 3 months ago

Additionally I could remove the properties on the _schema for which the value is undefined but that seems to be more of a bug than a feature:

    const properties = AjvTruckSchema['_schema'].properties;

    // remove
    Object.keys(properties['_schema'].properties).forEach((key) => {
      if (properties[key] === undefined) {
        delete properties[key];
      }
    });
thoroc commented 3 months ago

To add some more context. I have 2 scenarios where I can see the type and properties as unknown:

  1. When merging 2 schemas (such as the Car schema and the Truck schema)
  2. When using merged schemas in a union, but only the first schema seems to be then affected (see the Transport schema)
vitalics commented 2 months ago

@thoroc the issue will be fixed on next release

thoroc commented 2 months ago

Excellent thank you