对于Zod,我想获得一个可以访问的数组,并重用该数组来定义类型:
const TSchema= z.enum(‘a’, ‘b’, ‘c’); //hey, let's re-use this array as below!
type T = z.infer<typeof TSchema>;
//Gives me ‘type 'a’ | 'b' | 'c' <<<<<<<
//which is what I want, good!
但是,如果我这样做:
const arr = [‘a’,’b’,’c’] as readonly [string, …string[]];
const TSchema= z.enum(arr);
type T = z.infer<typeof TSchema>;
//Gives me ‘type T = string’, oh noes! <<<<<<<
//Why has the type changed?
//I want the union literal type above!
虽然我是用Zod来做的,但我认为这不是Zod特有的问题,我觉得这是一个通用的打字问题。请帮我看看:)
使用.enum
属性访问内容,并将其转换为数组:
const TSchema = z.enum(['a', 'b', 'c']);
const values = Object.values(TSchema.enum) // ("a" | "b" | "c")[]
TSchema.enum.a // "a"