Skip to content

Fix: Correct handling of identical minItems and maxItems in array schemas when arrayLength option is true #1784

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
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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/thick-geckos-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-typescript": patch
---

Fix: Correct handling of identical minItems and maxItems in array schemas when arrayLength option is true
10 changes: 8 additions & 2 deletions packages/openapi-typescript/src/transform/schema-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,8 +330,14 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor
(min !== 0 || max !== undefined) &&
estimateCodeSize < 30 // "30" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice
) {
// if maxItems is set, then return a union of all permutations of possible tuple types
if ((schemaObject.maxItems as number) > 0) {
if (min === max) {
const elements: ts.TypeNode[] = [];
for (let i = 0; i < min; i++) {
elements.push(itemType);
}
return tsUnion([ts.factory.createTupleTypeNode(elements)]);
} else if ((schemaObject.maxItems as number) > 0) {
// if maxItems is set, then return a union of all permutations of possible tuple types
const members: ts.TypeNode[] = [];
// populate 1 short of min …
for (let i = 0; i <= (max ?? 0) - min; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,20 @@ describe("transformSchemaObject > array", () => {
},
},
],
[
"options > arrayLength: true > minItems: 2, maxItems: 2",
{
given: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 2 },
want: `[
string,
string
]`,
options: {
...DEFAULT_OPTIONS,
ctx: { ...DEFAULT_OPTIONS.ctx, arrayLength: true },
},
},
],
[
"options > immutable: true",
{
Expand Down