how to define type Date in jsonSchemaType?

Viewed 85

I have an interface (using typescript) that I am building a Json schema for.

export interface IMyDate{

    FromDateUtc: Date,
    ToDateUtc: Date
}

this is how I defined the schema:

JSONSchemaType<IMyDate> = {

 type: "object",
    
properties: {
      
FromDateUtc: {
        type: "string",
        format: "date-time",
      },

ToDateUtc: {
        type: "string",
        format: "date-time",
      },

required: [
      "FromDateUtc",
      "ToDateUtc", 
    ],
   
 additionalProperties: false,
  
};

I am getting this error:

 The types of 'properties.FromDateUtc' are incompatible between these types.
    Type '{ type: "string"; format: string; }' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<Date, false> & { const?: Date | undefined; enum?: readonly Date[] | undefined; default?: Date | undefined; })'.

Any ideas why and how I can fix this?

2 Answers

In json-schema-to-typescript, We can use the tsType property in our JSON schema to override the type. tsType Overrides the type that's generated from the schema. Helpful in forcing a type to any or when using non-standard JSON schema extensions.

For Example, the JSON schema given below generates a type birthday with date as it's type.

const birthday = {
  name: `birthday `,
  type: `string`,
  tsType: `Date`,
  format: `date-time`,
}

export type birthday = Date;

date-time: A string instance is valid against this attribute if it is a valid representation according to the "date-time' ABNF rule

From json-schema-validation spec

So the string might be valid against this format but it is still a string. Try this:

export interface IMyDate {
    FromDateUtc: string;
    ToDateUtc: string;
}

According to JSON Schema Online Validator, the following is a valid JSON Schema:

{
    "title": "IMyDate",
    "type": "object",
    "properties": {
        "FromDateUtc": {
            "type": "string",
            "format": "date-time"
        },
        "ToDateUtc": {
            "type": "string",
            "format": "date-time"
        },
        "required": [
            "FromDateUtc",
            "ToDateUtc"
        ],
        "additionalProperties": false
    }
}

You could now use json-schema-to-typescript to extract the interface. The documentation of this tool states that format is "not expressible in TypeScript" and therefore the generated interface is the same as given above (with attributes of type string).

Note that there are several ways to convert a Date into a properly fomatted string.

Related