json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Feature request: option to generate const assertions for string enums

Open CNimmo16 opened this issue 3 years ago • 2 comments

Most easily explained with an example, if I have a definition in my schema as follows:

"color": {
  "$id": "#color",
  "type": "string",
  "enum": [
    "blue",
    "red",
    "yellow"
  ]
}

Currently this gets converted into a string union type directly ie. export type Color = "blue" | "red" | "yellow";

I'd like the option to convert these via a const assertion, emitting instead the following:

export const COLORS = ["blue", "red", "yellow"] as const;
export type Color = typeof COLORS[number];

Reason for this probably goes without saying - this would then allow the items to be accessed as values in code.

Could I get your thoughts on inclusion of this, would you accept a PR?

CNimmo16 avatar Jan 10 '22 12:01 CNimmo16

any updates on this? @bcherny could you point to a place in the code where one can look to begin a PR?

pyramation avatar May 05 '22 18:05 pyramation

Hey there! JSTT tries not to emit runtime code (notable exception: Enums). Let's leave this open, and see if others request this.

As a workaround, add tsEnumNames to your enum to emit it as a TS enum instead of a string union. We should maybe make this behavior the default, or a bit more obvious at some point.

bcherny avatar May 22 '22 06:05 bcherny