Skip to content

Commit

Permalink
feat(types): encode min length arrays into types
Browse files Browse the repository at this point in the history
Allows to encode into produced types the minnimum length of arrays.
  • Loading branch information
nfroidure committed Oct 9, 2023
1 parent 9528d27 commit 4d2279f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,33 @@ describe('generateTypeDeclaration()', () => {
`);
});

test('should create tuples from min length arrays', async () => {
const schema: JSONSchema7 = {
title: 'FixedArrayToTupleTest',
type: 'object',
additionalProperties: false,
required: ['data'],
properties: {
data: {
type: 'array',
items: { type: 'string' },
minItems: 2,
},
},
};

expect(toSource(await generateTypeDeclaration(context, schema)))
.toMatchInlineSnapshot(`
"export type FixedArrayToTupleTest = NonNullable<{
data: NonNullable<[
NonNullable<string>,
NonNullable<string>,
...NonNullable<string>[]
]>;
}>;"
`);
});

test('should work with tuples and rest test case schemas', async () => {
const schema: JSONSchema7 = {
title: 'TupleTest',
Expand Down
25 changes: 25 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,31 @@ async function buildArrayTypeNode(
);
}

// Switch from arrays to tuples and spread for small min length arrays
if (
'minItems' in schema &&
typeof schema.minItems === 'number' &&
schema.minItems > 0 &&
schema.minItems <
context.jsonSchemaOptions.tuplesFromFixedArraysLengthLimit
) {
return ts.factory.createTupleTypeNode(
new Array(schema.minItems)
.fill(
types.length > 1 ? ts.factory.createUnionTypeNode(types) : types[0],
)
.concat(
ts.factory.createRestTypeNode(
ts.factory.createArrayTypeNode(
types.length > 1
? ts.factory.createUnionTypeNode(types)
: types[0],
),
),
),
);
}

return ts.factory.createArrayTypeNode(
types.length > 1 ? ts.factory.createUnionTypeNode(types) : types[0],
);
Expand Down

0 comments on commit 4d2279f

Please sign in to comment.