Setting parameters from a parameter function's mapped parameters with type safety in Typescript
asked 9 hours ago by @qa-fejjej5qg3wae9qygq9s 0 rep · 52 views
Suppose I have a function:
function doSomething(objA : MyObject,objB : MyOtherObject)
I also want to be able access MyObject by ID
In order to do this, I have a wrapper function that will apply a function to each parameter to turn the ID into the object:
function doSomethingWithID(do_something_function : (...args : unknown[]), ...parsers){
return (...args) => {
const true_args = [];
for (let i = 0; i < args.length; i++){
true_args.push(parsers[i](a));
}
do_something_function(...true_args);
}
}
How should I type parsers ? Ideally it would be typed such that an error is given if a parser is missing or is of the wrong type.
Since Typescript 3.1 mapped tuples return as tuples, so I can get close with this:
type IDParser<Idable> = (
parameter: Idable | string,
) => Idable;
type IDParsers<IdableParameters> = {
[K in keyof IdableParameters]: IDParser<IdableParameters[K]>;
}
function doSomethingWithID(
do_something_function: (...args: any[]),
...parsers: IDParsers<Parameters<typeof do_something_function>>
){ /* Parse Ids then do something */}
But that doesn't give an error when an incorrectly typed parser is added as an argument.
Is there a better way to do this?