In typescript, an array can be converted to tuple by
type Arr = any[];
const f = < T extends Arr > (...args: [...T]): [...T] => {
return args;
}
const a = f(1, 'a'); // a is type of [number, string].
We can also map type by
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
How can I combine above two requirements into one? I tried
const h = <T extends keyof TypeMap>(...args: [...T[]]): [...TypeMap[T][]] => {
throw null;
}
const c = h('s', 'n');
However, c is type of (string|number)[] instead of [string, number].
I tried
const h = <T extends (keyof TypeMap)[]>(...args: [...T]): [...TypeMap[T[number]][]] => {
throw null;
}
but got the same c.
I found a solution using object instead of tuple, but tuple solution are welcome.
const f1 = <T extends keyof TypeMap>(...args: [...T[]]): {[P in T]: TypeMap[P]} => {
throw null;
}
const {s, n} = f1('s', 'n');