我正在使用 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))
关于javascript - 如何将 JS 字符串数组转换为与 io-ts 的联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65835382/