如何在JSONSchemaType中定义Date类型?类型不兼容问题排查
问题描述
我正在为以下TypeScript接口构建JSON Schema:
export interface IMyDate { FromDateUtc: Date, ToDateUtc: Date }
我的Schema定义如下:
const myDateSchema: JSONSchemaType<IMyDate> = { type: "object", properties: { FromDateUtc: { type: "string", format: "date-time", }, ToDateUtc: { type: "string", format: "date-time", }, }, required: [ "FromDateUtc", "ToDateUtc", ], additionalProperties: false, };
遇到了如下类型错误:
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; })'.
错误原因
TypeScript的Date类型与JSON中的string(date-time)类型存在映射差异:
- 接口字段为
Date类型,但Schema字段定义的是string类型,类型系统无法自动关联两者,认为Schema的类型(string)和接口的类型(Date)不匹配,从而抛出类型不兼容错误。 - 这里使用的
JSONSchemaType类型(通常来自type-fest或相关JSON Schema类型库)要求Schema定义必须严格对应TypeScript类型,直接写type: "string"会被识别为对应TypeScript的string类型,而非Date类型。
解决方法
需要在Schema的字段定义中明确指定该JSON字符串对应的TypeScript类型为Date,以对齐类型映射:
import type { JSONSchemaType } from 'type-fest'; export interface IMyDate { FromDateUtc: Date, ToDateUtc: Date } const myDateSchema: JSONSchemaType<IMyDate> = { type: "object", properties: { FromDateUtc: { type: "string", format: "date-time", tsType: Date // 明确对应TypeScript的Date类型 }, ToDateUtc: { type: "string", format: "date-time", tsType: Date // 明确对应TypeScript的Date类型 }, }, required: ["FromDateUtc", "ToDateUtc"], additionalProperties: false, };
如果使用的是其他JSON Schema类型库(如@types/json-schema),可通过类型断言临时解决,但更推荐使用支持tsType字段的库(如type-fest)实现类型安全的映射。
内容的提问来源于stack exchange,提问作者Talya Sterman
相关产品推荐
相关产品推荐

