ZOD distinguishes between unions based on two discriminator fields

I need to differentiate between two fields in a schema:

enum Action = {
    CREATE: 'create'
}

enum ObjectType = {
    Potatoe: 'potatoe',
    Tomatoe: 'tomatoe'
}

export const TestSchema = z.object({
  action: z.nativeEnum(Action),
  objectType: z.nativeEnum(ObjectType),
  payload: // need to discriminate based on both `action` and `objectType` values,
});

In the provided simplified example, I am looking to categorize the type of the payload depending on the values of both keys action and objectType.

discriminatedUnion [ref] Seems to only allow discrimination by one field

Answer №1

If you're looking to achieve this, the solution lies within the options property as detailed by colinhacks in response to a PR submitted for a comparable feature. Visit this link for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

TestCafe Environment Variables are not properly defined and displaying as undefined

Exploring TestCafe and diving into the world of automated testing. Trying to master the tools with guidance from Successfully executing code on my Windows setup! fixture`Getting Started`.page`http://devexpress.github.io/testcafe/example`; test("My ...

When working with React and Typescript, I encountered an issue with refs causing a typescript error: "The property 'current' does not exist on the type '(instance: HTMLInputElement | null) => void'"

I am working on a component that requires a ref prop: import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react' import styles from './index.module.css' import classNames from 'classnames' import { Ico ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

What is the best way to simulate mailgun.messages().send() with Jest?

Currently, I am utilizing the mailgun-js Api for sending emails. Instead of a unit test, I've created an integration test. I am now facing the challenge of writing a unit test case for the sendEmail method within the Mailgun class. I am unsure of how ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

What sets Interface apart from InstanceType<typeof Class> when used as a variable type?

Let's take a look at an example implementation: HttpService.ts: export interface IHttpService { request(): Promise<any>; formPostRequest(): any; } export class HttpService implements IHttpService { public async request() { // Implem ...

How can we update a boolean value in an Angular service using a set function?

Hey there! I'm currently working on updating a boolean value in my service when a button is clicked within my component. My goal is to trigger the setfunction and toggle the boolean value from true to false, and vice versa when the button is clicked a ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

"Using TSOA with TypeScript to return an empty array in the response displayed in Postman

I have successfully implemented CRUD operations using TSOA in TypeScript. However, I am facing an issue where I receive an empty array when making HTTP requests, despite adding data to the 'Livraison' table in MongoDB. https://i.sstatic.net/7IWT ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this: export class myapp { detail; myarr = ['me', 'myself', 'i']; title = this.myarr[0]; this.detail = this.title ; //error } I'm curious why `this.detail` ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

Issue with TypeScript Generics: The operand on the left side of the arithmetic operation must be of type 'any', 'number', or 'bigint'

I seem to be encountering an error that I can't quite decipher. Even though I've clearly set the type of first as a number, the code still doesn't seem to work properly. Can someone provide insights on how to fix this issue? function divide& ...

Creating an extended class with mandatory properties

In order to streamline code sharing between two classes that overlap, I decided to create a new class called Common. For one of the subclasses, I needed all the properties from the Common class to be required. My initial thought was to utilize the Require ...

Error message in React NodeJs stack: "The property ' ' does not exist on type 'never' in Typescript."

Recently, I have been immersing myself in learning NodeJs, Express, React, monogoDB and Typescript after working extensively with MVC C# SQL Databases. For my first project, I created a simple Hello World program that interacts with an Express server to d ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

Troubleshooting Next.js Mobile Freeze Issue: Unresponsive Scroll After Page Transition

Encountered a strange bug while testing my Next.js + Bootstrap demo project on mobile view. When using the burger menu to navigate to a new page on a mobile phone, attempting to scroll down causes it to stick/freeze/hang inexplicably. Despite my efforts to ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

Creating an interceptor to customize default repository methods in loopback4

Whenever I attempt to access the default repository code, I need to manipulate certain values before triggering the default crud function in the repository. How can I accomplish this? For example: ... @repository.getter('PersonRepository') priva ...