简体   繁体   English

如何在 Zod 中创建具有默认值的可选属性

[英]How to make an optional property with a default value in Zod

I'm using Zod and I want to define one schema for user input that has an optional field with a default value.我正在使用Zod ,我想为用户输入定义一个模式,该模式具有一个带有默认值的可选字段。 However, it is being impossible for me to make the runtime behaviour match the inferred type.但是,我不可能使运行时行为与推断的类型相匹配。 What I want, is the field to be optional, and when not provided, or provided as undefined, use the default value.我想要的是该字段是可选的,当未提供或未定义提供时,使用默认值。 If I want this behaviour I can't have the field optional in the generated type, and if I manage to make it optional in the generated type, then it will not get a default value during runtime.如果我想要这种行为,我不能在生成的类型中拥有可选的字段,并且如果我设法在生成的类型中使其成为可选,那么它在运行时将不会获​​得默认值。

Let me explain it with code:让我用代码解释一下:

import { Timestamp } from 'firebase/firestore';
import { z } from 'zod';

export const someSchema = z.object({
  id: z.string(),
  timestamp: z.instanceof(Timestamp),
  type: z.enum(['fever', 'constipation']),
  notes: z.string().optional().default(''),
});

export const someInput = someSchema
  .omit({ id: true })
  .merge(
    z.object({
      timestamp: z
        .date()
        .optional()
        .default(() => new Date()),
    }),
  )
  .partial({
    notes: true,
  });

export const schemaArray = z.array(someSchema);

export type Schema = z.infer<typeof someSchema>;
export type SchemaInput = z.infer<typeof someInput>; // <- Here I expect timestamp to be optional, but it is required


function a({ type, timestamp, notes}: SchemaInput){
  someInput.parse({
  type, timestamp, notes
  })
}

a({type: 'fever'}) <- Error, timestamp is required

As I was pointed out on github schemas usually have an input and an output type.正如我在 github 上指出的那样,模式通常具有输入和输出类型。 By default, what z.infer does is returning the output type, which is probably the most common usage scenario.默认情况下, z.infer所做的是返回输出类型,这可能是最常见的使用场景。 Thankfully there is also a method to extract the expected input for the parser, and that is exactly what I needed:值得庆幸的是,还有一种方法可以为解析器提取预期输入,而这正是我所需要的:

export type SchemaInput = z.input<typeof someInput>;

function a({ type, timestamp, notes}: SchemaInput){
  someInput.parse({
  type, timestamp, notes
  })

Now the inferred schema looks like this:现在推断的架构如下所示:

type SchemaInput = {
    timestamp?: Date | undefined;
    notes?: string | undefined;
    type: "fever" | "constipation";
}

Which is exactly what I needed for a function that takes this input and uses the validator to ensure it has the proper format.这正是我需要的一个函数,它接受这个输入并使用验证器来确保它具有正确的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Zod Schema:如何使字段可选或具有最小字符串约束? - Zod Schema: How to make a field optional OR have a minimum string contraint? 如何使一些函数参数可选,没有默认值,其他函数参数默认值? - How to make some function parameter optional without default value and others with default value? zod 中可选键的自定义验证 - Custom validation of optional keys in zod 使用 ReturnType&lt;&gt; 时如何使属性可选 - How to make property optional when using ReturnType<> 带有 zod 解析器可选字段的 React 挂钩表单 - React hook form with zod resolver optional field 在Typescript中,如果设置了另一个可选属性,如何使属性成为必需的? - In Typescript how to make a property required if another optional property is set? 如何使 TypeScript 解构 function 参数,分配默认值,以及可选的整个 object 类型? - How can I make TypeScript deconstruct function parameter, assign default value, and optional whole object type at same time? 如何使 Next.js“链接”的“href”属性可选 - how to make a Next.js "Link" 's "href" property optional 如何获取具有默认值的嵌套和可选对象值并定义类型? - How to get a nested and optional object value with a default value and define type? 如何使用zod检查确认密码 - How to check confirm password with zod
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM