javascript - 如何将 JS 字符串数组转换为与 io-ts 的联合?

标签 javascript typescript union-types fp-ts io-ts-library

我正在使用 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/

相关文章:

AngularJS 打印部分页面和数据绑定(bind)

node.js - 如何正确使用 TypeScript 联合类型?

javascript - 当您调用clear()然后在同一函数中设置一些本地存储值时不清除本地存储

javascript - JS : How would I display a decrementing value through an html header?(及更多)

java - sun.org.mozilla.javascript.internal.EcmaError : ReferenceError

visual-studio - 如何获得 Vue.js 2.0 typescript for TypeScript 与 Visual Studio 一起使用?

typescript - 出现错误 : Cannot find module 'js-yaml'

typescript - 在 TypeScript 中,如何将 Union 内的所有类型转换为该类型的数组

typescript - 是否可以在没有 "is not assignable to parameter of type ' never'"错误的情况下使用具有不同联合类型的数组元素?

javascript - 在javascript中替换url中的查询字符串