question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Array of objects with some of them literals

See original GitHub issue

How are you? I’m thinking about the following validation with zod and I have no clue on how to do it (or if it’s possible with zod). I want an array of objects, all with the same shape of course with some of them with literal props, I need these always present in the array.

Example: I need always in the array the objects those with name required1 and required2, and then other objects optionals following the same shape.

[
    {
      name: z.literal('required1'),
      otherprop: z.number()
    },
    {
      name: z.literal('required2'),
      otherprop: z.number()
    },
    // I want to include one or more of the following too.
    {
      name: z.string(),
      otherprop: z.number()
    },
]

This other example will throw because required2 is missing

[
    {
      name: z.literal('required1'),
      otherprop: z.number()
    },
    // I want to include one or more of the following too.
    {
      name: z.string(),
      otherprop: z.number()
    },
]

Any clue?

Thanks.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
scotttrinhcommented, Oct 29, 2021

I’m going to close this, but feel free to post your solution here when you’re done if you come up with something that you like!

0reactions
Lzokcommented, Nov 4, 2021

I solved it doing the following (simplified here)

const elementSchema = z.object({
  name: z.string(),
  otherprop: z.number(),
})
type Element = z.infer<typeof elementSchema>;

function refineNames(elements: Element[]): boolean {
	// In my real code, here I have a function that returns the array of required names for the case.
       const names = ['required1', 'required2'];

       return names.every((el: string) => elements.some(x => x.name === el));
}

function hasDuplicates(elements: Element[]): boolean {
	const names = elements.map(e => e.name);

	return names.length !== new Set(names).size;
}

z.array(elementSchema).superRefine((elements, ctx) => {
		if (refineNames(elements)) {
			ctx.addIssue({
				code: z.ZodIssueCode.custom,
				message: `There are missing names. Required names are ${names.join(', ')}`,
			});
		}

		if (hasDuplicates(elements)) {
			ctx.addIssue({
				code: z.ZodIssueCode.custom,
				message: 'No duplicated name allowed.',
			});
		}
	}),

Thanks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Is there a way to have an array of objects with some of them ...
I want an array of objects, all with the same shape, with some of them with literal props, I need these always present...
Read more >
JavaScript Fundamentals: Object Literals and Nested Arrays
An associative array indexes elements differently; usually with a word for each slot, making it far more structured and readable. Unfortunately, ...
Read more >
JavaScript Literals - w3resource
In Javascript, an array literal is a list of expressions, each of which represents an array element, enclosed in a pair of square...
Read more >
JavaScript Object Literals Simplified - Standardista
The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after...
Read more >
Data Structures: Objects and Arrays - Eloquent JavaScript
Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate typeof [] , it produces "object"...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found