ThomasAribart / json-schema-to-ts

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

FromSchema returns unknown (code example) #152

Closed nabilfreeman closed 1 year ago

nabilfreeman commented 1 year ago

Code to reproduce:

import { JSONSchema, FromSchema } from 'json-schema-to-ts';

export const TestSchema: JSONSchema = {
    type: 'object',
    properties: {
        id: { type: 'number' },
    },
    additionalProperties: false,
} as const;

export type TestColumns = FromSchema<typeof TestSchema>;

// TestColumns is type `unknown`

TS version: 5.0.4 Library version: ^2.9.1

Also tried downgrading to 2.8.2

A bit sad as I was very excited to use this library! 🥺

nabilfreeman commented 1 year ago

I figured this out last night - It's because I typed TestSchema as JSONSchema instead of using satisfies.

Here is the working code:

import { JSONSchema, FromSchema } from 'json-schema-to-ts';

export const TestSchema = {
    type: 'object',
    properties: {
        id: { type: 'number' },
    },
    additionalProperties: false,
} as const satisfies JSONSchema;

export type TestColumns = FromSchema<typeof TestSchema>;

// TestColumns is type `{ id: number }`
nabilfreeman commented 1 year ago

Closing. I think this should help unblock somebody searching for "unknown" in the future. 👍

ThomasAribart commented 1 year ago

Nice !