vega / ts-json-schema-generator

Generate JSON schema from your Typescript sources
MIT License
1.44k stars 190 forks source link

Handle const like enum with only one option #1899

Closed UzairNoman closed 2 weeks ago

UzairNoman commented 6 months ago

Need a way to handle this problem in the generator: https://github.com/json-editor/json-editor/pull/1446

The inspiration repo implements it with optional paramater --constAsEnum Use enums with a single value when declaring constants.:

https://github.com/YousefED/typescript-json-schema

vladimir-prisada commented 5 months ago

One more vote for this. For example, AWS API Gateway models are defined using the JSON schema draft 4 and it would be very useful to have enum instead of constant in the schema

domoritz commented 5 months ago

Happy to review a pull request. I won't be able to make time to implement this feature since I don't need it for my use case.

vladimir-prisada commented 2 weeks ago

Alternative way is to use custom formatter https://github.com/vega/ts-json-schema-generator?tab=readme-ov-file#custom-formatting


import { EnumType, EnumTypeFormatter } from "ts-json-schema-generator";

class CustomEnumTypeFormatter extends EnumTypeFormatter {
  public getDefinition(type: EnumType): Definition {
    const result = super.getDefinition(type);

    if ("const" in result && result.const) {
      return { type: result.type, enum: [result.const] };
    }

    return result;
  }
}
domoritz commented 2 weeks ago

Would you like to send a pull request with this feature?

0nua commented 2 weeks ago

@domoritz , how can I create a pull request? I am getting permissions denided on pushing my branch

domoritz commented 2 weeks ago

You make a fork, push to your fork, send a pull request from there. You have full permissions to push to your fork.

domoritz commented 2 weeks ago

As discussed in https://github.com/vega/ts-json-schema-generator/pull/2073#issuecomment-2357262748, we want a simple behavior here and https://github.com/vega/ts-json-schema-generator/issues/1899#issuecomment-2356131944 is a great solution for anyone who needs special behavior.