Encountered an issue while attempting to construct a Fastify-Zod validation schema

Exploring the world of TypeScript, I recently ventured into using zod for validating my fastify request/response. However, I hit a roadblock while trying to build schemas using the fastify-zod plugin as it resulted in a compile error. This dilemma revolves around my user.schema.ts

import { z } from 'zod'
import { buildJsonSchemas } from 'fastify-zod';

export enum Role {
    Agent = 'Agent',
    Admin = 'Admin',
}

const createUserSchema = z.object({
    email: z.string({
        required_error: "Email is required",
        invalid_type_error: "Email must be a string"
    }).email(),
    role: z.nativeEnum(Role, {
        required_error: "Role is required"
    }),
    teamId: z.number({
        required_error: "Team id is required"
    })
});

export type CreateUserInput = z.infer<typeof createUserSchema>;

export const { schemas: userSchemas, $ref } = buildJsonSchemas({
    createUserSchema     //error here (compile)
});

The issue arises at the createUserSchema with an accompanying error message:

(property) createUserSchema: z.ZodObject<{
    email: z.ZodString;
    role: z.ZodNativeEnum<typeof Role>;
    teamId: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
    email: string;
    role: Role;
    teamId: number;
}, {
    email: string;
    role: Role;
    teamId: number;
}>
Property 'brand' is missing in type 'ZodObject<{ email: ZodString; role: ZodNativeEnum<typeof Role>; teamId: ZodNumber; }, "strip", ZodTypeAny, { email: string; role: Role; teamId: number; }, { ...; }>' but required in type 'ZodType<unknown, ZodTypeDef, unknown>'.ts(2741)
    types.d.ts(78, 5): 'brand' is declared here.
    Models.d.ts(2, 59): The expected type comes from property 'createUserSchema' which is declared here on type 'Models<string>'

I am puzzled by this unfamiliar presence of:

Property 'brand' is missing in type

Do you have any insights into what might be causing this hiccup?

Edit:

These are the dependencies listed in my package.json file:

  "dependencies": {
    "@firebase/app-types": "^0.7.0",
    "@prisma/client": "^4.3.1",
    "dotenv": "^16.0.2",
    "fastify": "^4.6.0",
    "fastify-cors": "^6.1.0",
    "fastify-zod": "^1.2.0",
    "firebase": "^9.9.4",
    "firebase-admin": "^11.0.1",
    "zod": "3.18.0",
    "typescript": "4.8.2"
  },

After updating zod version to 3.18.0 from 3.17.2, I encountered this new obstacle:

Type instantiation is excessively deep and possibly infinite.ts(2589)

Answer №1

Using the `zod` library in conjunction with `fastify-zod` can lead to some unexpected errors caused by outdated package versions.

When you combine `email protected]` and `emailprotected]`, you might encounter errors related to missing 'brand' properties:

Property 'brand' is missing in type 'ZodObject; teamId: ZodNumber; }, "strip", ZodTypeAny, { email: string; role: Role; teamId: number; }, { ...; }>' but required in type 'ZodType'.ts(2741)
    types.d.ts(78, 5): 'brand' is declared here.
    Models.d.ts(2, 59): The expected type comes from property 'createUserSchema' which is declared here on type 'Models'

If you utilize `emailprotected]` and `emailprotected]`, or if your TypeScript version is below v4.1, you may run into deeply nested instantiation errors:

Type instantiation is excessively deep and possibly infinite.ts(2589)

However, when you update both packages to their latest versions (currently `emailprotected]` and `emailprotected]`), everything should function as intended.

Check out this TypeScript playground 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

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

Using JSDoc with TypeScript's generic types: A guide

Can you provide some guidance on the best way to use JSDoc for generic TypeScript functions? I attempted to implement it as shown below, but received a prompt suggesting that JSDoc types may be moved to TypeScript types.ts(80004). When I clicked on the "q ...

implementing custom data fetching with TypeScript using generics is the way to go

Having a useFetch function that requires a URL argument of type string to consume an API, I encountered an issue where the result is not being recognized. The useFetch function uses generic types, and everything runs smoothly when using the types defined i ...

Developing bespoke styles in Angular Material 2

I am in the process of developing a unique theme for my Angular 2 application, incorporating various components from angular material 2. Despite searching extensively online, I haven't been able to find much relevant information. The only documentati ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Is there a way to access URL parameters in the back-end using Node.js?

How can I extract querystring parameters email, job, and source from the following URL? I want to use these parameters in my service class: @Injectable() export class TesteService{ constructor(){} async fetchDataFromUrl(urlSite: URL){ ...

Encountering a problem with data types in React TypeScript Context

Currently delving into TypeScript with React and facing some challenges. I've set up cart.context.tsx but encountering this error: (property) React.ProviderProps<AppContextInterface>.value: AppContextInterface Type '{ isCartOpen: boolean; s ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Locate the minimum and maximum values between two inputted dates

I'm looking for a solution that provides strongly typed code. The problem arises when trying to implement solutions from a related question - Min/Max of dates in an array? - as it results in an error. TS2345: Argument of type 'Date' is not ...

Implementing JavaScript Code in TypeScript

Every JavaScript code should also be valid in TypeScript, but when attempting to run the following code snippet below, an error is triggered. Could someone convert this JavaScript code into TypeScript? Error: 20:9 - TS2531 Error: Object is possibly 'z ...

Using the simplebar library does not effectively hide the horizontal scrolling bar

Utilizing the simplebar library (https://github.com/Grsmto/simplebar) within a project built on Angular 6 has presented an issue. Upon adding the simple bar to my HTML tag, both horizontal and vertical scroll bars appeared. My goal is to display only the v ...

What is the specific type of event for a change handler in TypeScript?

As a newcomer to TypeScript, I recently crafted a change handling function that accepts the event as a parameter to assign the value, like event.target.value. Currently, I have designated this as any, but I suspect there is a more appropriate type for this ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

What could be causing the lack of updates to my component in this todo list?

Based on my understanding, invoking an action in MobX should trigger a rerender for the observer. However, when I call the handleSubmit method in my AddTask component, it doesn't cause the TaskList observer to rerender. Should I also wrap AddTask in a ...

Angular removing every query string parameters

Linked to but distinct from: How to maintain query string parameters in URL when accessing a route of an Angular 2 app? I am facing an issue with my basic Angular application where adding a query parameter results in its removal, both from the browser&apo ...

Creating a Typescript version of the mongodb project aggregation functionality

Present scenario: I am currently working on creating a type-safe wrapper for the node-mongodb driver. I am facing challenges in determining the return type for the project aggregation stage. Feel free to check out the TypeScript Playground here class Base ...

What is the process for converting variadic parameters into a different format for the return value?

I am currently developing a combinations function that generates a cartesian product of input lists. A unique feature I want to include is the ability to support enums as potential lists, with the possibility of expanding to support actual Sets in the futu ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...