ThomasAribart / json-schema-to-ts

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

Properties with const are not typed as const. #174

Closed floratmin closed 4 months ago

floratmin commented 8 months ago

When a schema has a property with const value, then the inferred type should also be const. E.g.:

const schema = {
  $id: 'myschema',
  title: 'MySchema',
  type: 'object',
  required: ['myprop'],
  additionalProperties: false,
  properties: {
    myprop: {
      const: 500,
    },
  },
} as const;

type Schema = FromSchema<typeof schema>;

This works if I use Schema directly. But if I make some type transformations this gets lost and the type of myprop becomes number, because there is no readonly annotation for this property.

schema: {
  readonly $id: "myschema", 
  readonly title: "MySchema",
  readonly type: "object",
  readonly required: readonly ["myprop"],
  readonly properties: {
    myprop: 500
  },
  readonly additionalProperties: false
};
ThomasAribart commented 7 months ago

@floratmin as const is actually recursive so I think the issue probably comes from your type transformation.

I can try to help you on that but it doesn't seem to be an issue with the lib.

ThomasAribart commented 4 months ago

@floratmin Just realized that you miss a const keyword just before your 500 constant:

schema: {
  readonly $id: "myschema", 
  readonly title: "MySchema",
  readonly type: "object",
  readonly required: readonly ["myprop"],
  readonly properties: {
    myprop: { const: 500 } // <= here
  },
  readonly additionalProperties: false
};

Wether your props are readonly or not should not be an issue after v3. I have tried and it works fine. Closing the issue.