【发布时间】:2021-04-20 03:20:10
【问题描述】:
在打字稿中,数组可以通过以下方式转换为元组
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 variadic-tuple-types