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

Apparently there is no option to generate non nullable model properties

Open gyozob opened this issue 2 years ago • 4 comments

Hello, is there a way to generate non nullable model properties? Whatever I do it always generates as nullable.

// Current
export type SampleModel= {
    title?: string;
    url?: string;
};

// Expected
export type SampleModel= {
    title: string;
    url: string;
};

In my swagger json I also added these properties as required but I got the same result. I'm using this command npx openapi-typescript-codegen --input $swaggerUrl --output ./src/interfaces/--exportCore=false --exportServices=false

gyozob avatar Dec 15 '22 12:12 gyozob

Yes, instead of:

SampleModel:
    type: object
    properties:
      title:
        type: string
      url:
        type: string

Use:

SampleModel:
    required:
      - title
      - url
    type: object
    properties:
      title:
        type: string
      url:
        type: string

See the spec for more info.

predrag-codetribe avatar Jan 23 '23 07:01 predrag-codetribe

I also was a bit curious about what is correct here

so basically string? in typescript does not mean nullable but optional, then it makes sense

nullable in typescript would be string | null

atlemagnussen avatar Mar 10 '23 09:03 atlemagnussen

This is the same issue as https://github.com/ferdikoomen/openapi-typescript-codegen/issues/1300. The solution is to change the schema. If using NSwag have a look at https://github.com/RicoSuter/NSwag/issues/3110#issuecomment-799519820.

alexanderchr avatar Oct 04 '23 17:10 alexanderchr

But how do I make C# property:

[Required]
 public string? PaymentMethodId { get; set; }

to generatea:

paymentMethodId: string | null;

Adding attribute required always makes it non-nullable. Removing it alwats make it optional and nullable doesn't matter if it's optional in C#

Any suggestions?

abbjetmus avatar Feb 01 '24 10:02 abbjetmus