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

Add option to represent non-required properties as required fields in TS with `| undefined`

Open Gelio opened this issue 1 year ago • 4 comments

Description

Proposal

I suggest adding an option that would determine whether non-required object properties get turned into:

  someProperty?: string;

or

  someProperty: string | undefined;

The latter seems safer to work with as a producer of objects that have to match the generated TypeScript types. When adding a new non-required property to an object, I want TypeScript to point out to me all the places in which I should consider adding/skipping that property.

Right now after adding a new non-required property, TypeScript will happily accept existing code, since those existing objects are still valid, because the property is optional. If the property was declared as required, but undefinable (| undefined), I would have to manually go through all the places where that property should appear and either set it to a valid value, or set it to someProperty: undefined (if it should be omitted).

I understand this is a breaking change, which is why I suggest making it a CLI option, rather than changing the default behavior.

For reference, ts-proto has a useOptionals option that decides whether optional properties are generated using ? or | undefined. They recommend | undefined as the default behavior (the behavior I want also from openapi-typescript).

Checklist

Gelio avatar Apr 04 '24 14:04 Gelio

This issue is stale because it has been open for 90 days with no activity. If there is no activity in the next 7 days, the issue will be closed.

github-actions[bot] avatar Aug 06 '24 12:08 github-actions[bot]

Bump, since IMO this is still worth it.

Gelio avatar Aug 06 '24 12:08 Gelio