最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to transform a JS array of strings into a union with io-ts? - Stack Overflow

programmeradmin1浏览0评论

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. 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. I just don't know how.

The end result in this case should be (with io-ts):

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

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. 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. I just don't know how.

The end result in this case should be (with io-ts):

export const ControlType = t.union(
  t.literal("section"),
  t.literal("text"),
  t.literal("richtext"),
  t.literal("number"),
);
Share Improve this question edited Aug 9, 2022 at 17:40 0Valt 10.4k9 gold badges39 silver badges64 bronze badges asked Jan 21, 2021 at 20:38 Obed ParlapianoObed Parlapiano 3,7323 gold badges25 silver badges40 bronze badges 3
  • what do you mean by the word "union"? – dandavis Commented Jan 21, 2021 at 20:41
  • should've been more explicit, updated the question @dandavis – Obed Parlapiano Commented Jan 21, 2021 at 21:23
  • i don't do ts, but it looks like that could be t.union(... CONTROLS.map(t.literal));, as long as t.literal just expects one argument, otherwise you need a map wrapper to call just one arg. – dandavis Commented Jan 21, 2021 at 21:25
Add a ment  | 

1 Answer 1

Reset to default 8

io-ts formally remends to use keyof for better performance with string literal unions. 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))
发布评论

评论列表(0)

  1. 暂无评论