我有一个对象
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;我需要和佐德一起用它
"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>;但是,我不想定义我的数据两次,一次用标签(标签用于ui目的),另一次没有标签。
我只想使用properties对象定义一次,而不使用VALUES数组,并使用它创建zod对象并从zod对象推断类型。
有什么解决办法吗?
发布于 2022-09-23 09:00:52
在这种情况下,我想我可以从Property直接推断出properties的类型。您可以避免重复使用如下代码:
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);https://stackoverflow.com/questions/73825273
复制相似问题