Skip to content

Commit c2f8655

Browse files
authored
Fix: Correct handling of identical minItems and maxItems in array schemas 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
1 parent c3f4bc4 commit c2f8655

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

.changeset/thick-geckos-compete.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-typescript": patch
3+
---
4+
5+
Fix: Correct handling of identical minItems and maxItems in array schemas when arrayLength option is true

packages/openapi-typescript/src/transform/schema-object.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -330,8 +330,14 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor
330330
(min !== 0 || max !== undefined) &&
331331
estimateCodeSize < 30 // "30" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice
332332
) {
333-
// if maxItems is set, then return a union of all permutations of possible tuple types
334-
if ((schemaObject.maxItems as number) > 0) {
333+
if (min === max) {
334+
const elements: ts.TypeNode[] = [];
335+
for (let i = 0; i < min; i++) {
336+
elements.push(itemType);
337+
}
338+
return tsUnion([ts.factory.createTupleTypeNode(elements)]);
339+
} else if ((schemaObject.maxItems as number) > 0) {
340+
// if maxItems is set, then return a union of all permutations of possible tuple types
335341
const members: ts.TypeNode[] = [];
336342
// populate 1 short of min …
337343
for (let i = 0; i <= (max ?? 0) - min; i++) {

packages/openapi-typescript/test/transform/schema-object/array.test.ts

+14
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,20 @@ describe("transformSchemaObject > array", () => {
146146
},
147147
},
148148
],
149+
[
150+
"options > arrayLength: true > minItems: 2, maxItems: 2",
151+
{
152+
given: { type: "array", items: { type: "string" }, minItems: 2, maxItems: 2 },
153+
want: `[
154+
string,
155+
string
156+
]`,
157+
options: {
158+
...DEFAULT_OPTIONS,
159+
ctx: { ...DEFAULT_OPTIONS.ctx, arrayLength: true },
160+
},
161+
},
162+
],
149163
[
150164
"options > immutable: true",
151165
{

0 commit comments

Comments
 (0)