如何将JS字符串数组转换为与io-ts的联合?



我正在使用io-ts,我想知道是否有一种方法可以将字符串数组(字面量)转换为这种字面量的联合。例如:

export const CONTROLS = [
"section",
"text",
"richtext",
"number",
];
export const ControlType = t.union(
// What to do here? Is this even possible? This is what came to mind but it's obviously wrong.
// CONTROL_TYPES.map((type: string) => t.literal(type))
);

我不知道这是否可能,但考虑到io-ts只是JS函数,我不明白为什么不。我只是不知道该怎么做。

在这种情况下的最终结果应该是(带io-ts):

export const ControlType = t.union(
t.literal("section"),
t.literal("text"),
t.literal("richtext"),
t.literal("number"),
);

io-ts正式推荐使用keyof以获得字符串字面值联合的更好性能。值得庆幸的是,这也使这个问题更容易解决:

export const CONTROLS = [
"section",
"text",
"richtext",
"number",
] as const;
function keyObject<T extends readonly string[]>(arr: T): { [K in T[number]]: null } {
return Object.fromEntries(arr.map(v => [v, null])) as any
}
const ControlType = t.keyof(keyObject(CONTROLS))

最新更新