Zod Entry using standard encryption key

I'm attempting to define an object type in zod that looks like this:

{
    default: string,
    [string]: string,
}

I've experimented with combining z.object and z.record using z.union, but the validation results are not as expected.

const LocaleString = z.union([
  z
    .object({
      default: z.string(),
    }).required(),
  z.record(z.string()),
]);

LocaleString.safeParse({
  testing: 'abc',
}); 
/** 
* it will return `{ success: true, data: { testing: 'abc' } }`, 
* where I expect it to fail when the data is without a default value
*/

Answer №1

After some investigation, I discovered a solution that worked perfectly in my situation.

const LanguageStrings = z.object({
  default: z.string(),
}).and(z.record(z.string()));

LanguageStrings.safeParse({
  default: '123',
}); // passes successfully

LanguageStrings.safeParse({
  en: '123',
}); // fails to pass

LanguageStrings.safeParse({}); // fails to pass

LanguageStrings.safeParse({
  default: 'abc',
  en: 'def',
}); // passes successfully

Answer №2

If you want to avoid strict validation, you can modify the object.

Sample Schema:

z.object({
  default: z.string()
})

Data:

{
  default: 'circle',
  example: true
}

Outcome:

Validation Passed

Data:

{
  example: true
}

Outcome:

Validation errors: 
[
  { path: "default", error: "Required" },
]

By applying .strict() to the object() definition, the initial data will not pass validation.

Sample Schema:

z.object({
  default: z.string()
}).strict()

Data:

{
  default: 'circle',
  example: true
}

Outcome:

Validation errors: 
[
  { error: "Unrecognized key(s) in object: 'example'" },
]

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

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Facing issues with module resolution while attempting to debug in VSCode

I'm currently in the process of debugging a module within our project. However, I've encountered difficulties attaching the debugger on Visual Studio Code since we recently changed the directory structure. Here is my tsconfig: { "compilerOptio ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

The type '{}' is lacking the specified attributes from type 'RouteComponentProps<{},,>'

As a newcomer to React and Typescript, I'm in the process of familiarizing myself with both. Please bear with me as I navigate through this learning curve! index.tsx Router.tsx (containing all route definitions) LandingFrame.tsx (defining the page la ...

The attribute 'location' is not found in the 'File' data type

Recently, I made the switch from using multer to multer-s3 in my project. I have updated the controllers accordingly to store the "location" instead of the "filename". However, I am encountering a typescript error. At the moment, I am utilizing Localstack ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

3 Ways to Ensure Your Picture Uploads are Visible Right Away

I am currently working on an Ionic app that enables users to upload images to Firebase storage. One issue I am encountering is that the image only changes once a new one is selected, after closing and reopening the app. I would like it to update immediatel ...

When declaring an array of numbers in sequelize-typescript, it triggers a TypeScript error

In my application, I am working with PostgreSQL, Sequelize, Sequelize-TypeScript, and TypeScript. I have a need for a table called Role where each role has multiple permissions of type integer. I'm following the guidelines provided in the sequelize-ty ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Implementing debounce in Subject within rxjs/Angular2

I am currently building an events service, and here is the code snippet I am using: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; export int ...

What is the reason behind Webpack's behavior of loading all files from a folder during lazy loading

I am attempting to dynamically import i18n files using webpack: function getI18n(lang) { return import(/* webpackChunkName "i18n/[request]" */ `./locales/${lang}.json`) .then(/*whatever*/) } However, I have noticed that all the files from the specifi ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Troubleshooting Issue with Mongoose Virtual Field Population

I am currently facing an issue with my database due to using an outdated backend wrapper (Parse Server). The problem arises when dealing with two collections, Users and Stores, where each user is associated with just one address. const user = { id: &q ...

Tips for choosing a subset of objects within a larger array of objects and generating a new array from them?

I am working with an array of 3586 objects, each containing various products. How can I create and store a new array that only includes the products from a specific index? console.log listarPorReferencia() { this.linxService.listarPorReferencia().subs ...

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

Ways to obtain a tab and designate it as the default in angular when using angular material Tabs

I am facing an issue with accessing tabs within a nested component. The parent component contains the tab feature and to reach the tabs inside the child component, I am using the following code: document.querySelectorAll('.mat-tab-group'); The a ...