ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.43k stars 30 forks source link

Problem with dates #155

Closed javierguzman closed 11 months ago

javierguzman commented 1 year ago

Hello all,

I have these two schemas:

export const layerSchema = {
  type: 'object',
  properties: {
    id: uuidSchema,
    name: {
      type: 'string',
      minLength: 2,
      maxLength: 80,
    },
    description: {
      type: 'string',
      minLength: 2,
      maxLength: 2000,
    },
    shortDescription: {
      type: 'string',
      minLength: 2,
      maxLength: 200,
    },
    createdAt: {
      type: 'string',
      format: 'date-time',
    },
  },
  additionalProperties: false,
  required: ['id', 'name', 'shortDescription', 'createdAt'],
} as const;

export const layerResponseSchema = {
  type: 'object',
  properties: {
    layer: layerSchema,
    blablablabla
    }

Then, I generate the response type like this:

export type LayerResponse = FromSchema<typeof layerResponseSchema>;

And now if I create a LayerResponse object, Typescript complains because foundLayer.created_at is Date, while createdAt is string:

let layer: LayerResponse = {
      layer: {
        id: foundLayer.id,
        createdAt: foundLayer.created_at,
        name: foundLayer.name,
        shortDescription: foundLayer.short_description,
      },
      blablabla
}

I saw #26 and I thought my example would work. Is this a bug or am I missing something along the way?

Thank you in advance and regards

ThomasAribart commented 11 months ago

@javierguzman Did you read the section about deserialization in the README ? Your use-case is exactly the example provided in it: https://github.com/ThomasAribart/json-schema-to-ts#deserialization

You miss a deserialize option in FromSchema:

export type LayerResponse = FromSchema<
  typeof layerResponseSchema,
  {
    deserialize: [
      {
        pattern: {
          type: 'string';
          format: 'date-time';
        };
        output: Date;
      },
    ];
  }
>;