ThomasAribart / json-schema-to-ts

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

Refs are not working #114

Closed HiiiiD closed 1 year ago

HiiiiD commented 1 year ago

Simple refs are not working due to a broken TS check. Here's a reproducible example:

const ref = {
    $id: 'refElement',
    type: 'string',
    default: '',
    enum: ['1', '2', '3', '']
} as const;

const elem = {
    type: 'object',
    additionalProperties: false,
    properties: {
        refKey: { $ref: 'refElement' }
    }
} as const;

type Result = FromSchema<typeof elem, { references: [typeof ref] ]}>

This returns:

type Result = { refKey?: never; }

After digging in the codebase I found the issue and it's a broken check:

// lib/types/parse-schema/references/utils.d.ts
P extends string ? <do-a-thing> : <do-another>

But P can be undefined and undefined extends string returns true If we revert the check, so string extends undefined than it works because string doesn't extend undefined

ThomasAribart commented 1 year ago

Hi @HiiiiD ! Can you try with v2.7.2 ? It seems like it's fixed