What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object?

For instance, in ES5 you can achieve the following:

const person = {
   firstName: "John",
   lastName: "Doe",
   get fullName() {return `${this.firstName} ${this.lastName}`}
}
person.fullName => "John Doe"

Answer №1

When it comes to the "Comparison" section, you can find information in the zod documentation referring to:

Runtypes

https://github.com/pelotom/runtypes

This library offers good support for type inference and includes read-only types functionality, which is not present in Zod.

Therefore, it's worth noting that Zod does not have support for read-only properties.


Nevertheless, the following code snippet demonstrates a working example:

import { z } from "zod";

const meUnknown: unknown = {
  firstName: "Testy",
  lastName: "mcTestface",
  get myName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

const MeSchema = z.object({
  firstName: z.string(),
  lastName: z.string(),
  myName: z.string()
});

const me = MeSchema.parse(meUnknown);
/* The `me` variable has a type of:
{
    firstName: string;
    lastName: string;
    myName: string;
}
*/

console.log(me.myName);

You may refer to this sandbox for further details.

However, it should be noted that Zod does not produce an error at the type level when assigning a new value like in the following example:

me.myName = 'something' // no type error here

This behavior is due to the fact that Zod lacks support for read-only types.

Answer №2

If you have a clear vision of the object's shape that you want to create, then you can utilize a transform function to organize your parsed data into an instance of a class containing read-only properties:

class Person {
  public constructor (
    public name: string,
    public age: number,
  ) {}
  
  public get info() {
    return `${this.name} is ${this.age} years old`;
  }
}

const structure = z.object({
  name: z.string(),
  age: z.number(),
}).transform(
  ({ name, age }) => new Person(name, age)
);

const individual = structure.parse({ name: 'Alice', age: 30 });
console.log(individual.info); // 'Alice is 30 years old'

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

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Converting Angular 2/TypeScript classes into JSON format

I am currently working on creating a class that will enable sending a JSON object to a REST API. The JSON object that needs to be sent is as follows: { "libraryName": "temp", "triggerName": "trigger", "currentVersion": "1.3", "createdUser": "xyz", ...

What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types For example: type Foo = string | number I need to receive this type and convert it into an array of the individual types within the union type TransformedFoo = ToUnionOfArray<Foo> // => string[] ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

Issue when trying to use both the name and value attributes in an input field simultaneously

When the attribute "name" is omitted, the value specified in "value" displays correctly. However, when I include the required "name" attribute to work with [(ngModel)], the "value" attribute stops functioning. Without using the "name" attribute, an error ...

The name "Identifier" has already been declared before

I am currently working on a social network project to enhance my skills in nodejs and reactjs. While debugging the backend code for /signin using Postman, I encountered an error that prevents me from launching the node server. The error message displayed i ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Angular 2 - Issue: Parameters provided do not correspond to any signature of call target

I'm encountering the following error message: "error TS2346: Supplied parameters do not match any signature of call target." This occurs when attempting to reject a promise, but I believe the code adheres to the required signatures. Any suggestions on ...

Using mergeMap in conjunction with retryWhen allows for the resumption of retries from the exact point of failure, without needing

I have a list of URLs, the number of which is unknown until it stops (depending on some condition). This is how I am currently using them: from(observableUrls) .pipe( mergeMap(url => callHttpService(url) , 4), retryWhen( // Looking f ...

The utilization of paths in tsconfig.json does not successfully resolve when working with Angular

I'm trying to set up Angular to understand paths in order to avoid using relative paths when importing files. However, despite my efforts, it doesn't seem to be working. Here is my code snippet: //tsconfig.app.json "compilerOptions":{ //lot ...

Prevent coverage tracking for files or paths enclosed in square brackets in jest

I am trying to exclude a specific file from test coverage in Jest by modifying the collectCoverageFrom array. The file name contains square brackets, and I have added an entry with a negation for this file. collectCoverageFrom: [ './src/**/*.{js ...

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

The module 'json-stringify-safe' could not be located

Encountering an issue while executing the command - ionic serve The code was functioning properly on a different system but seems to be causing trouble for me at the moment. ...

What steps can I take to avoid encountering the `@typescript-eslint/unbound-method` error while utilizing the `useFormikContent()` function?

Recently, I updated some of the @typescript-eslint modules to their latest versions: "@typescript-eslint/eslint-plugin": "3.4.0", "@typescript-eslint/parser": "3.4.0", After the update, I started encountering the fo ...

Exploring Polymorphism in Typescript through Data Model Interfaces

Seeking out a design pattern for the following scenario: IApp.ts export interface IApp { platform: PlatformEnum; version: string; islive: boolean; title: string; iconurl: string; } IAppleApp.ts export interface IAppleApp extends IApp { ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

Using TypeScript absolute imports from another project for standard TypeScript files and declarations at a global scope

We are currently considering migrating a large JavaEE code base to TypeScript. Within this environment, there are multiple projects with intricate directory structures and JavaScript code that heavily relies on global variables across all projects. Althou ...

What could be the reason for passport.serializeUser function not being available?

After spending nearly an hour searching, I am still unable to pinpoint the issue in my code. Not only have I failed to find a solution online, but reaching out for help in coding communities on Discord has also been futile as no one seems to know why this ...