typescript 从对象创建zod枚举

bvn4nwqk  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(130)

我有这个对象

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" },
] as const;

我需要和佐德一起使用它
1.在后端验证和解析我的数据
1.使用这些可能的值"entire_place" | "shared_room" | "private_room"创建类型脚本联合类型
根据
zod文档**,我可以这样做:

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" },
] as const;

const VALUES = ["entire_place", "private_room", "shared_room"] as const;
const Property = z.enum(VALUES);
type Property = z.infer<typeof Property>;

然而,我不想定义我的数据两次一次使用标签(标签用于用户界面),另一次没有标签
我只想使用properties对象定义它一次,而不使用VALUES数组,然后使用它创建一个zod对象并从zod对象推断类型。
怎么解决?

piah890a

piah890a1#

在这种情况下,我想我会直接从properties中推断出Property的类型,这样就可以避免重复使用如下代码:

import { z } from "zod";

const properties = [
  { value: "entire_place", label: "The entire place" },
  { value: "private_room", label: "A private room" },
  { value: "shared_room", label: "A shared room" }
] as const;

type Property = typeof properties[number]["value"];
// z.enum expects a non-empty array so to work around that
// we pull the first value out explicitly
const VALUES: [Property, ...Property[]] = [
  properties[0].value,
  // And then merge in the remaining values from `properties`
  ...properties.slice(1).map((p) => p.value)
];
const Property = z.enum(VALUES);

相关问题