简体   繁体   English

使用 IO-TS 将 JS 字符串数组转换为 union

[英]Transform a JS array of strings into a union with IO-TS

I'm using io-ts and i'm wondering if there's a way to turn an array of strings (literals) into a union of such literals.我正在使用io-ts ,我想知道是否有办法将字符串(文字)数组转换为此类文字的联合。 For example:例如:

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))
);

I don't know if this is possible but given that io-ts is just JS functions I don't see why not.我不知道这是否可能,但鉴于io-ts只是 JS 函数,我不明白为什么不这样做。 I just don't know how.我只是不知道怎么做。

The end result in this case should be (with io-ts):在这种情况下,最终结果应该是(使用 io-ts):

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

io-ts formally recommends to use keyof for better performance with string literal unions. io-ts 正式推荐使用keyof以获得更好的字符串文字联合性能。 Thankfully, that also makes this problem much easier to solve:值得庆幸的是,这也使这个问题更容易解决:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM