RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.38k stars 532 forks source link

TypeScript generation with EnumStyle `StringLiteral` and defaults #1618

Closed nycdotnet closed 11 months ago

nycdotnet commented 1 year ago

I am generating TypeScript code for an API with a MyClass schema defined like this:

myProperty:
  type: "string"
  enum:
  - "ABC"
  - "DEF"
  - "GHI"
  default: "ABC"

I am generating with /enumStyle:StringLiteral. This will correctly generate the type for myProperty which looks like this:

export type MyClassMyProperty = "ABC" | "DEF" | "GHI";

However, when the default is used within the init method of MyClass, it still tries to use enum syntax which gives an error:

this.myProperty= _data["myProperty"] !== undefined ? _data["myProperty"] : MyClassMyProperty.ABC;

I think this was just an oversight during the implementation of #1137 . I am going to attempt to address this.

nycdotnet commented 1 year ago

I am preparing a fix that overrides GetEnumDefaultValue in TypeScriptValueGenerator and changes the behavior if something like the below is true:

typeResolver is TypeScriptTypeResolver tsr && tsr.Settings.EnumStyle == TypeScriptEnumStyle.StringLiteral
nycdotnet commented 11 months ago

Hooray! I can confirm that upgrading NSwag.MSBuild to the latest preview (14.0.0-preview008) fixes our TypeScript generation issue!