Skip to content

fix: correctly transform untyped nullable field #1468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/large-ways-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-typescript": patch
---

Correctly transform untyped nullable fields to `unknown`
2 changes: 1 addition & 1 deletion packages/openapi-typescript/src/transform/schema-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ export function defaultSchemaObjectTransform(schemaObject: SchemaObject | Refere
}

// nullable (3.0)
if (schemaObject.nullable) finalType = tsUnionOf(finalType || "Record<string, unknown>", "null");
if (schemaObject.nullable) finalType = tsUnionOf(finalType || "unknown", "null");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 this was really old code that someone argued that “object types” were the default type, but I couldn’t find anything in the spec suggesting that. Anyways, this is a good change to make.


if (finalType) return finalType;

Expand Down
5 changes: 5 additions & 0 deletions packages/openapi-typescript/test/schema-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,11 @@ describe("Schema Object", () => {
const generated = transformSchemaObject({}, options);
expect(generated).toBe(`unknown`);
});

test("unknown nullable", () => {
const generated = transformSchemaObject({ nullable: true }, options);
expect(generated).toBe(`unknown`);
});
Copy link
Contributor Author

@davejsdev davejsdev Nov 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue suggested the type should be unknown | null, but unknown is effectively the same, and tsUnionOf() won't do a union if the type is already unknown; it just returns unknown.

});

describe("schema composition", () => {
Expand Down