[英]Transform a JS array of strings into a union with 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.