3

我正在使用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"),
);
4

1 回答 1

6

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))
于 2021-01-22T01:32:10.697 回答