pydantic-to-typescript icon indicating copy to clipboard operation
pydantic-to-typescript copied to clipboard

Field with default value becomes optional on the TypeScript interface

Open robbieaverill opened this issue 3 years ago • 1 comments

Example:

class MyModel(BaseModel):
  my_bool_property: bool = False

Convert to TypeScript and see output:

interface MyModel {
  my_bool_property?: bool;
}

I believe that the interface shouldn't define the property as optional, since Pydantic will ensure it is hydrated with the default value of false if it's not provided when creating models, e.g.:

newModel = MyModel()
assert newModel.my_bool_property is False  # assertion passes

Expected TypeScript interface:

interface MyModel {
  my_bool_property: bool;
}

robbieaverill avatar Oct 17 '22 18:10 robbieaverill

I think that can go either way, so the result should be optional. For example, if I'm writing a client for an API the body of the request is going to look like this

interface MyModel {
  my_bool_property?: bool;
}

But the response would not be optional because Pydantic handles to null types for us

interface MyModel {
  my_bool_property: bool;
}

Really, I need both of them when build an API client, or I'd need to strictly define the request body and the response body with different defaults on the backend as two different models.

hay-kot avatar Oct 18 '22 22:10 hay-kot