繁体   English   中英

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

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

我正在使用Zod ,我想为用户输入定义一个模式,该模式具有一个带有默认值的可选字段。 但是,我不可能使运行时行为与推断的类型相匹配。 我想要的是该字段是可选的,当未提供或未定义提供时,使用默认值。 如果我想要这种行为,我不能在生成的类型中拥有可选的字段,并且如果我设法在生成的类型中使其成为可选,那么它在运行时将不会获​​得默认值。

让我用代码解释一下:

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

正如我在 github 上指出的那样,模式通常具有输入和输出类型。 默认情况下, z.infer所做的是返回输出类型,这可能是最常见的使用场景。 值得庆幸的是,还有一种方法可以为解析器提取预期输入,而这正是我所需要的:

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

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

现在推断的架构如下所示:

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

这正是我需要的一个函数,它接受这个输入并使用验证器来确保它具有正确的格式。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM