openapi-ts / openapi-typescript

Generate TypeScript types from OpenAPI 3 specs
https://openapi-ts.dev
MIT License
5.75k stars 460 forks source link

Inconsistent behavior for optional properties with defaults #1957

Open Gero-B opened 3 hours ago

Gero-B commented 3 hours ago

Description

I've discovered inconsistent behavior when generating types for optional fields which also provide a default value. See sandbox for more info

Given a simple Item schema:

"Item": {
    "type": "object",
    "properties": {
        "status": { "type": "string", "nullable": true, "default": "complete" },
    }
}

Depending on where it is defined in the openapi spec file we get different results:

If we define Item in the endpoint directly without using a ref we get:

"application/json": {
    /** @default complete */
    status?: string; // correct behavior
};

If we define Item in components and use a ref in the endpoint spec the result becomes:

Item: {
    /** @default complete */
    status: string; // this is now no longer optional
};

The latter behavior is unexpected and incorrect as the field should not be required

Name Version
openapi-typescript 7.4.1
Node.js 20.12.1

Reproduction

https://codesandbox.io/p/devbox/openapi-typescript-optional-default-5zjvsz

see spec.json input file and output.d.ts result

Checklist

Gero-B commented 3 hours ago

Jus found this - https://github.com/openapi-ts/openapi-typescript/issues/1903 seems to be the same issue