Skip to content
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

feat(types): encode min length arrays into types #32

Merged
merged 1 commit into from
Oct 9, 2023
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
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