Skip to content

fromTypes() generates invalid {"type":"Date"} in OpenAPI schema #308

@0-don

Description

@0-don

The fromTypes() function generates invalid OpenAPI schemas when TypeScript types contain Date objects. The generated schema shows {"type":"Date"} instead of {"type":"string","format":"date-time"}.

Reproduction

openapi({
  references: fromTypes('src/index.ts')
})

// TypeScript return type: { createdAt: Date }
// Generated schema: { "createdAt": { "type": "Date" } }
// Expected: { "createdAt": { "type": "string", "format": "date-time" } }

Root Cause

Underlying @sinclair/typemap library doesn't parse Date correctly from declaration strings.

Suggested Fix

Add post-processing in declarationToJSONSchema() to transform {"type":"Date"}{"type":"string","format":"date-time"} until upstream fix is available.

Implementation

function transformDateTypes(schema: any): any {
  if (!schema || typeof schema !== 'object') return schema

  if (schema.type === 'Date') {
    return { type: 'string', format: 'date-time' }
  }

  if (schema.properties) {
    const transformed: any = { ...schema }
    transformed.properties = Object.fromEntries(
      Object.entries(schema.properties).map(([key, value]) => [
        key,
        transformDateTypes(value)
      ])
    )
    return transformed
  }

  if (schema.items) {
    return { ...schema, items: transformDateTypes(schema.items) }
  }

  if (schema.anyOf || schema.oneOf || schema.allOf) {
    const key = schema.anyOf ? 'anyOf' : schema.oneOf ? 'oneOf' : 'allOf'
    return {
      ...schema,
      [key]: schema[key].map(transformDateTypes)
    }
  }

  return schema
}

export function declarationToJSONSchema(declaration: string) {
  const schema = TypeBox(declaration)
  return transformDateTypes(schema)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions