Skip to content

Commit

Permalink
Fix: Correct handling of identical minItems and maxItems in array sch…
Browse files Browse the repository at this point in the history
…emas when arrayLength option is true (#1784)

* Fix: Correct handling of minItems and maxItems with identical values in array schemas

- Resolved issue where the generated interface was [] when minItems and maxItems were identical
- Now generates a tuple type for such cases
- Added test case for OpenAPI specification with minItems and maxItems set to 2

* chore: run lint fix
  • Loading branch information
yoshi2no authored Jul 29, 2024
1 parent c3f4bc4 commit c2f8655
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
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

0 comments on commit c2f8655

Please sign in to comment.