openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

Default value and required in generated Type

Open lucabergamini opened this issue 3 years ago • 0 comments

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 ?

lucabergamini avatar Jul 28 '22 15:07 lucabergamini