typescript 具有可空字段的Zod对象模式

jvidinwx  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

我想定义一个Zod模式,其中所有属性都可以为空。目前我定义它如下,并为每个属性重复nullable()。有没有更好的方法来避免重复?PS.对于那些建议使用.Partial的人:它不会**使对象字段为空。

const MyObjectSchema = z
  .object({
    p1: z.string().nullable(),
    p2: z.number().nullable(),
    p3: z.boolean().nullable(),
    p4: z.date().nullable(),
    p5: z.symbol().nullable(),
  })
  .partial();
tpgth1q7

tpgth1q71#

你可以在对象上使用partial方法或deepPartial方法。

const MyObjectSchema = z.object({
 p1: z.string(),
 p2: z.string(),
 p3: z.string(),
 p4: z.string(),
 p5: z.string(),
}).partial();

在上面的例子中,你只需要partial方法,因为你没有处理嵌套结构。
如果你正在处理一个嵌套对象,使用partial还是deepPartial取决于你,如下所示。

/*
    DeepPartialObjectSchema will allow the location field to be nullable.
    If an object is provided for the location field,
    the houseNo and country field will also be optional (i.e., nullable).
    You can provide the location object and still omit or not include any of the fields in the location object.
*/

const DeepPartialObjectSchema = z.object({
 name: z.string(),
 age: z.string(),
 location: z.object({
    houseNo: z.string(),
    country: z.string()
  })
}).deepPartial();

/*
    PartialObjectSchema will also allow the location field to be nullable.
    However, if an object is provided for the location field,
    then the object must include the houseNo and country field.
    Either you provide all the required fields in the location object
    or don't provide the location object at all.
*/

const PartialObjectSchema = z.object({
 name: z.string(),
 age: z.string(),
 location: z.object({
    houseNo: z.string(),
    country: z.string()
  })
}).partial();

对于partial和deepPartial方法,location字段将是可选的(即,可空)。但是使用partial方法还是deepPartial方法取决于在提供location字段时是否需要houseNo和country字段。

注意:也可以只将选定字段设为空

// only p1 and p2 will be made nullable.
// p3, p4, p5 will remain required.
const MyObjectSchema = z.object({
 p1: z.string(),
 p2: z.string(),
 p3: z.string(),
 p4: z.string(),
 p5: z.string(),
}).partial({ p1: true, p2: true });

相关问题