首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeScript:将包含字符串联合的对象类型映射到返回结果中

问TypeScript:将包含字符串联合的对象类型映射到返回结果中
EN

Stack Overflow用户
提问于 2021-04-27 21:15:27
回答 2查看 40关注 0票数 0

这是这个问题的扩展:TypeScript: return a union of the input string array's literal values?

这个问题扩展了最后一个问题,将文字元组嵌入到对象的任意键中,并将它们映射到输出键上。

代码语言:javascript
复制
function myfn<T extends string>(opts: { [key: string]: T[] }) {
  const out: ??? = {};
  for (const [key,val] of Object.entries(opts)) {
    out[key] = val[0];
  }
  return out;
}

const result = myfn({
  foo: ['a', 'b', 'c'],
  bar: ['x', 'y', 'z'],
})

// Expected: {
//   foo: 'a' | 'b' | 'c',
//   bar: 'x' | 'y' | 'z',
// }

myfn中/上需要什么类型才能获得预期的类型?

我知道这与Mapped Types有关,但我不知道它到底是什么。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-27 22:32:40

现在还没有完整的答案,但这就是你要找的类型:

代码语言:javascript
复制
type MapToUnion<T extends { [key: string]: readonly string[] }> =
    {
        -readonly [K in keyof T]: T[K][number]
    }

const opts = {
    foo: ['a', 'b', 'c'],
    bar: ['x', 'y', 'z'],
} as const;

type Mapped = MapToUnion<typeof opts>;

// type Mapped = {
//     foo: "a" | "b" | "c";
//     bar: "x" | "y" | "z";
// }
票数 1
EN

Stack Overflow用户

发布于 2021-04-28 00:12:02

Freenode上的用户systemfault在##typescript中写了这个解决方案:

代码语言:javascript
复制
type MyFnResult<T extends string, Options extends {readonly [k:string]: T[]}> = Options extends any? { [K in keyof Options]: Options[K][number] } : never

function myfn<
  T extends string,
  Options extends {readonly [k:string]: T[] }
>(opts: Options): MyFnResult<T, Options> {
  const out: Record<string, string> = {};

  for (const [key,val] of Object.entries(opts)) {
    out[key] = val[0];
  }
  return out as any
}

const result = myfn({
  foo: ['a', 'b', 'c'],
  bar: ['x', 'y', 'z'],
})

// Out type: {
//   foo: 'a' | 'b' | 'c',
//   bar: 'x' | 'y' | 'z',
// }

它起作用了。我一点也不明白。但它是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67283810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档