ferdikoomen / openapi-typescript-codegen

NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification
MIT License
2.79k stars 513 forks source link

Default value and required in generated Type #1168

Open lucabergamini opened 1 year ago

lucabergamini commented 1 year ago

Describe the bug Hi all, not sure if this is expected (I've seen it was discussed in some other issues like https://github.com/ferdikoomen/openapi-typescript-codegen/pull/727) but here is my issue:

I've a model defined as:

class MyClass(pydantic.BaseModel):
    prop_1: str = "test_default"
    prop_2: int = 1

which is exported as:

      "MyClass": {
        "title": "MyClass",
        "type": "object",
        "properties": {
          "prop_1": {
            "title": "Prop 1",
            "type": "string",
            "default": "test_default"
          },
          "prop_2": {
            "title": "Prop 2",
            "type": "integer",
            "default": 1
          }
        }
      },

Now, the generated type is:

export type MyClass = {
    prop_1?: string;
    prop_2?: number;
};

which completely removes the default. I guess this does not break the contract because you can provide an instance of the type without the values to a server, and those values will be set to default in validation.

However, it forces me to work with values which can be undefined on the client side (even though they won't be in practice).

Typescript Type does not support defaults as it's a compile time info, so I guess there is no easy way of fixing this without changing what gets generated.

Is this the expected behaviour? what is the best practice to work with client-generated MyClass ?

hrstmr commented 1 year ago

@lucabergamini you can mark the prop_1 and prop_2 as required by adding it to the list "required": ["prop_1","prop_2"], something like this 👇

"MyClass": {
  "title": "MyClass",
  "required": ["prop_1","prop_2"],
  "type": "object",
  "properties": {
    "prop_1": {
      "title": "Prop 1",
      "type": "string",
      "default": "test_default"
    },
    "prop_2": {
      "title": "Prop 2",
      "type": "integer",
      "default": 1
    }
  }
}

which should generate the type definition of

export type MyClass = {
    prop_1: string;
    prop_2: number;
};
blipk commented 1 year ago

This is a regression, looks like it was fixed in #551 but I'm still having the same issue in 0.23.0

Editing the openapi.json spec file is not really reasonable, non-Optional fields with a default value should NOT be marked as optional in the generated typescript, yet they are.

hueindahaus commented 1 year ago

Please fix this one. It's extremely annoying to have fields possibly undefined when the specification says otherwise

CavalcanteLeo commented 1 year ago

any update about this?