Broaden your interfaces by implementing multiple interfaces with Zod

Utilizing typescript, I am able to incorporate multiple interfaces

interface Name {
 name: string
}

interface Age {
 age: number
}

interface People extends Name, Age {
 height: number
}

Is there a similar way to achieve this with Zod?

What I attempted

const nameZ = z.object({ name: z.string() })
const ageZ = z.object({ age: z.number() })

const peopleZ = z.object({ hieght: z.number }).merge(nameZ).merge(ageZ)

However, the code appears messy and is difficult to comprehend. Are there any alternative solutions?

Thank you

Answer №1

If you're looking to streamline your code, there are a few options available. One approach is to utilize the .extend method as the final step in your chain of methods. This eliminates the need for typing out z.object() repeatedly. Another possibility is to rearrange the sequence of merges. In cases where you have numerous schemas to merge, creating a function might be beneficial, although this could result in losing some TypeScript type information unless you come up with a workaround.

import { z } from "zod";

const nameZ = z.object({ name: z.string() })
const ageZ = z.object({ age: z.number() })

const peopleZ  = z.object({ height: z.number() }).merge(nameZ).merge(ageZ)
const peopleZ2 = nameZ.merge(ageZ).extend({ height: z.number() })
const peopleZ3 = nameZ.merge(ageZ).merge(z.object({ height: z.number() }))

https://tsplay.dev/abc123

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

What is the reason behind taps in TypeScript only registering the first tap event?

One issue I am encountering is that only the first tap works when clicked, and subsequent taps result in an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') Here is the code I am using: https://codepen ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Utilize the authenticated page across various tests in Playwright for efficient testing

Starting out fresh with playwright and node.js frameworks Currently in the process of developing a framework using playwright with typescript. Everything was smooth sailing until I reached the point where I needed to run my tests sequentially on the same ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

"Utilize TypeScript to create a function that can handle either a single value or

I am attempting to develop a double function with the following structure: type MaybeArray<T> = T | T[]; function double<T extends MaybeArray<number>>(data: T): T extends number[] ? number[] : number { if (Array.isArray(data)) { / ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

Error message: "IAngularStatic type does not have property IScope" caused by Typescript Directives

I'm working on creating an Angular Directive using TypeScript to share a scope item. I created an interface that inherits from ng.IScope, but Visual Studio Code is showing me a warning: "Property IScope does not exist on type IAngularStatic". I am usi ...

Unable to load dynamic JSON data in ag-grid for Angular 2

ngOnInit(){ this.gridOptions = {}; this.gridOptions.rowData = []; this.gridOptions.rowData = [ {configName: 1, configName1: "Jarryd", configName2: "Hayne", configName3: "tttttt", configName4: "rrrtttt", configName5:"drrrrrr"}]; } ...

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

MSBUILD encounters numerous JQuery errors when compiling a web project with TypeScript

Currently, I am working on a .net core 3.1 (netcoreapp3.1) razor pages project that includes typescript files and a few javascript files. The project builds perfectly from Visual Studio 2019 (professional) as well as from the command line using MSBuild. H ...

`Achieving efficient keyboard navigation with MUI Autocomplete and SimpleBar integration in React``

Currently, I am attempting to integrate the Simplebar scrollbar into the MUI Material Autocomplete component in place of the default browser scrollbar. While everything is functioning correctly, this customization has caused me to lose the ability to use t ...