zod
zod copied to clipboard
variadic rest in the tuple with min & max capability
I have a scenario, where I need to define the schema in the form of a tuple with certain restrictions in length of min, and max on the variadic rest.
const TypeOneSchema = z.object({
name: z.string(),
value: z.number(),
});
const TypeTwoSchema = z.object({
title: z.string(),
amount: z.number(),
});
const TupleSchema = z.tuple([
TypeOneSchema, **// First element: TypeOneSchema**
z.array(TypeTwoSchema).min(1).max(3) **// Rest elements: 1 to 3 TypeTwoSchema**
]);
Note: The above syntax of the tuple isn't supported, adding it here for a better understanding of the use case.
Say something like this: For example: the scenario is that a tuple can be a minimum of 2 items & at max, it can have 4 items in the array.
// Example usage
Valid
const validTuple1 = [ { name: 'John', value: 20 }, { title: 'Title 1', amount: 100 } ];
const validTuple2 = [ { name: 'John', value: 20 }, { title: 'Title 1', amount: 100 }, { title: 'Title 2', amount: 150 } ];
Invalid
const invalidTuple1 = [ {name: 'John', value: 20 } ];
const invalidTuple2 = [ { name: 'John', value: 20 }, { title: 'Title 1', amount: 100 }, { title: 'Title 2', amount: 150 }, { title: 'Title 3', amount: 200 }, ];
Please suggest how to achieve this using tuple, because it also gives the benefit of auto-suggestion in the code-editor.
I'll provide an idea: first, define a tuple(typeA, ...typeB). This way, you can handle the first type and the remaining types. As for the length restriction, you can use an array, but the array only deals with the count, so the values handled by min() and max() need to be increased by one.
const TupleSchema = z
.tuple([TypeOneSchema])
.rest(TypeTwoSchema)
.and(z.array(z.any()).min(2).max(4)); // not 1 and 3
Hi, @ram2104. I'm Dosu, and I'm helping the Zod team manage their backlog. I'm marking this issue as stale.
Issue Summary:
- You raised an issue about defining a tuple schema in Zod with a fixed object type as the first element and a variadic array of another object type with specific length constraints.
- You were looking for a solution that supports code-editor auto-suggestions.
- @sunnylost suggested using a combination of
tupleandrestmethods, along with an array to enforce the length constraints, which resolved the issue.
Next Steps:
- Please let us know if this issue is still relevant to the latest version of the Zod repository. If so, you can keep the discussion open by commenting on the issue.
- Otherwise, the issue will be automatically closed in 7 days.
Thank you for your understanding and contribution!
In Zod 4:
const TypeOneSchema = z.object({
name: z.string(),
value: z.number(),
});
const TypeTwoSchema = z.object({
title: z.string(),
amount: z.number(),
});
const TupleSchema = z.tuple([TypeOneSchema], TypeTwoSchema).check(
z.minLength(5),
z.maxLength(10),
);