Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use.
type MapParamsToFunction<A extends any[]> = [[...params: A], (...args: A) => void]
function asMap<A extends any[]>(map: MapParamsToFunction<A>): MapParamsToFunction<A> {
return map;
}
asMap([[],() => {}]) // good
asMap([[0, "Hello World", 2], (a: number, b: string, c: number) => { }]); // good
asMap([[0, "Hello World", 2], (a: number, b: number, c: number) => { }]); // error
asMap([[0, "Hello World"], (a: number, b: string, c: number) => { }]); // error
Everything is working fine so far. Now, I want to extend this concept and create a dictionary where each key can contain a different set of parameters/arguments. But, I'm facing a challenge in getting TypeScript to allow a unique generic type for each key.
I attempted using any[]
in the type definition, but it doesn't provide a type error if the parameters and arguments don't match.
type FunctionDictionary<T extends string> = {
[K in T]: MapParamsToFunction<any[]>
}
function asDictionary<T extends string>(dict: FunctionDictionary<T>): FunctionDictionary<T> {
return dict;
}
let obj = asDictionary({
"foo": [[0, "Hello World", 2], (a: number, b: number, c: number) => { }], // no type error
"bar": [["","",""], (a: string, b: string, c: string) => { }]
});
Is there a way to achieve individual generic parameter lists for each argument in the mapping?
type FunctionDictionary<T extends string> = {
[K in T]: MapParamsToFunction<?> // <--- that's the puzzle
}