这是这个问题的扩展:TypeScript: return a union of the input string array's literal values?
这个问题扩展了最后一个问题,将文字元组嵌入到对象的任意键中,并将它们映射到输出键上。
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有关,但我不知道它到底是什么。
发布于 2021-04-27 22:32:40
现在还没有完整的答案,但这就是你要找的类型:
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";
// }发布于 2021-04-28 00:12:02
Freenode上的用户systemfault在##typescript中写了这个解决方案:
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',
// }它起作用了。我一点也不明白。但它是有效的。
https://stackoverflow.com/questions/67283810
复制相似问题