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

Literal fields are converted to optional any

Open DavidRowthorn opened this issue 1 year ago • 5 comments

Using version 0.26.0

A class like the following:

class Animal(BaseModel):
    type: Literal["dog"] = "dog"
    name: string

Should generate a typescript class like so:

export type Animal = {
  type: "dog"
  name: string
}

But it generates

export type Animal = {
  type?: any
  name: string
}

DavidRowthorn avatar Jan 31 '24 11:01 DavidRowthorn

@DavidRowthorn I'll need to see the spec you're using to generate the client, are you able to provide it? You can also try running your spec against our fork, this issue might be fixed there.

mrlubos avatar Feb 29 '24 00:02 mrlubos

@mrlubos I have got the same issue on my end, tried even with your fork but Literal declarations are being generated as optional. However I am not sure if this is entirely generators fault as you see in the schema and not sure if this is somehow configurable during the schema generation.

{
  "Person":{
    "title":"Person",
    "type":"object",
    "properties":{
      "id":{
        "title":"Id",
        "type":"string"
      },
      "type":{
        "title":"Type",
        "default":"Young",
        "enum":[
          "Young"
        ],
        "type":"string"
      },
      "created":{
        "title":"Created",
        "type":"string",
        "format":"date-time"
      }
    },
    "required":[
      "id",
      "created"
      // type is not added as required here
      ...
      ...
    ]
  }
}

elibolonur avatar Mar 11 '24 10:03 elibolonur

@elibolonur do you generate spec from code or is it written manually? If code, are you able to share the snippet responsible for the piece that you shared?

EDIT: the original post is about literals not being treated as such and outputting any, but you're talking about an optional field, i.e. not the same issue

mrlubos avatar Mar 11 '24 15:03 mrlubos

@mrlubos Unfortunately not able to share the full schema. This is the part that is treated as optional, with changed names. I could share this part with some changed names fully as well.

Also yes, it is not exactly the same. However it is probably still related since literal types are translated as optional anyway. Might not be related to the generator either as said.

elibolonur avatar Mar 11 '24 16:03 elibolonur

@DavidRowthorn @elibolonur this is fixed in the latest version of @nicolas-chaulet/openapi-typescript-codegen. If you're ending up with an optional field, you will need to mark it as required in your schema and that will resolve that problem!

mrlubos avatar Mar 16 '24 04:03 mrlubos