【问题标题】:Transform a JS array of strings into a union with IO-TS使用 IO-TS 将 JS 字符串数组转换为 union
【发布时间】:2021-01-21 20:38:42
【问题描述】:

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

【问题讨论】:

  • “联合”这个词是什么意思?
  • 应该更明确,更新问题@dandavis
  • 我不做 ts,但看起来可能是 t.union(... CONTROLS.map(t.literal));,只要 t.literal 只需要一个参数,否则你需要一个地图包装器来调用一个 arg。

标签: javascript typescript fp-ts


【解决方案1】:

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

【讨论】:

  • 这是上面的 ControlType 代码生成的:` t.KeyofC. Which is correct since it'll only get keyOf`
猜你喜欢
  • 2018-02-18
  • 2011-08-22
  • 2014-04-08
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 2022-11-18
  • 2023-01-12
  • 2019-03-14
相关资源
最近更新 更多