将数组转换为映射类型元组的 Typescript 函数签名

Typescript function signature that converts an array to tuple of mapped type

在打字稿中,数组可以通过

转换为元组
type Arr = any[];
const f = < T extends Arr > (...args: [...T]): [...T] => {
  return args;
}

const a = f(1, 'a'); // a is type of [number, string].

我们也可以通过

映射类型
type TypeMap = {
    'n': number;
    's': string
};

const g = <T extends keyof TypeMap>(args: T): TypeMap[T] => {
    throw null;
}

const b = g('s'); //b is type of string

如何将以上两个要求合二为一?我试过了

const h = <T extends keyof TypeMap>(...args: [...T[]]): [...TypeMap[T][]] => {
    throw null;
}
const c = h('s', 'n');

然而,c 是 (string|number)[] 的类型而不是 [string, number]。 我试过了

const h = <T extends (keyof TypeMap)[]>(...args: [...T]): [...TypeMap[T[number]][]] => {
    throw null;
}

但得到了相同的 c.

我找到了一个使用对象而不是元组的解决方案,但欢迎使用元组解决方案。

const f1 = <T extends keyof TypeMap>(...args: [...T[]]): {[P in T]: TypeMap[P]} => {
    throw null;
}
const {s, n} = f1('s', 'n');

typescript playground

您想使用 mapped tuple. Given T, a tuple type, {[I in keyof T]: ...T[I]...} will be another tuple type; the I only iterates over numeric indices of T. Note that due to a bug/limitation in TypeScript (see microsoft/TypeScript#27995) the compiler doesn't realize that T[I] will be the element type of T, so you have to use some trick like the Extract utility type

在您的例子中,从输入元组 T 扩展 Array<keyof TypeMap>,您希望输出元组在数字索引 I 处具有类型 TypeMap[T[I]] 的元素:

const h = <T extends (keyof TypeMap)[]>(...args: [...T]): {
    [I in keyof T]: TypeMap[Extract<T[I], keyof TypeMap>]
} => {
    throw null;
}

const c = h('s', 'n'); // [string, number] 

Playground link to code