Optional parameters with `default` are generated as required
Description
An optional field in the openapi schema that includes the default property is generated as required in typescript
| Name | Version |
|---|---|
openapi-typescript |
7.4.3 |
| Node.js | 18.19 |
| OS + version | macOS 14.2.1 |
Reproduction
The following openapi schema is used:
{
"openapi": "3.1.0",
"info": {
"title": "Config Service",
"version": "local"
},
"paths": {
"/config": {
"post": {
"summary": "Set Config",
"operationId": "set_config_v1_config_post",
"parameters": [],
"requestBody": {
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/ConfigIn"
},
{
"type": "null"
}
],
"title": "Params"
}
}
}
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "null",
"title": "Response Set Config Post"
}
}
}
}
}
},
}
},
"components": {
"schemas": {
"ConfigIn": {
"properties": {
"interval": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"title": "Interval",
"default": 1
},
"start_at": {
"anyOf": [
{
"type": "string",
"format": "date-time"
},
{
"type": "null"
}
],
"title": "Start At"
}
},
"type": "object",
"required": [],
"title": "ConfigIn"
}
}
}
}
Running npx openapi-typescript ./schema.json -o ./types.ts
The following type for ConfigIn is generated:
ConfigIn: {
/**
* Interval
* @default 1
*/
interval: number | null;
/** Start At */
start_at?: string | null;
};
Expected result
I expect interval to be marked optional as well
ConfigIn: {
/**
* Interval
* @default 1
*/
interval?: number | null;
/** Start At */
start_at?: string | null;
};
Checklist
- [ ] My OpenAPI schema passes the Redocly validator (
npx @redocly/cli@latest lint) - [ ] I’m willing to open a PR (see CONTRIBUTING.md)
Possible duplicate of https://github.com/openapi-ts/openapi-typescript/issues/1957
I'm currently handling this bug with post-processing. I wrote a janky Python script to parse the generated schema.d.ts file and fix the output for the cases described in this issue
It'd be great to get this fix into the library!
Add the flag --default-non-nullable false when generating schema.
He is right, `--default-non-nullable false' solves the problem. I think this is intended, because this default value is not essentially set on the code end, after all.
My code got bitten by this issue. I was previously using version 6 or earlier. The --default-non-nullable false fix worked.
Respectfully, I'd like to understand why this new command line parameter is needed. I checked a few versions, and it appears versions 7.0 through 7.8 now convert optional properties with a default value to required, unless I specify --default-non-nullable false. Shouldn't optional properties remain optional, regardless of the existence of a default value?