Assume I have methods
that are defined in the following way:
const methods = {
methodOne(a: string) { return a; },
methodTwo(a: number) { return a; },
methodThree() {}
} as const;
I am able to deduce the type of methods
:
type MethodDefinitions = typeof methods;
Now, let's consider a scenario where I want to create a function that has the ability to execute any method from methods
like this:
function doSomething<T extends keyof MethodDefinitions>(t: T, arg: Parameters<MethodDefinitions[T]>[0]) {
const method = methods[t];
method(arg);
}
In this case, I anticipate method
to infer a specific type based on T
and methods
. However, TypeScript playground reveals that the type of method
is
(a: never) => string | number | void
, and raises an error when attempting to call method
with arg
.
How can this issue be resolved without resorting to using any
? One workaround is casting arg
to never
(method(arg as never)
), but this solution may not be ideal.
Visit TS playground for further reference: link.