I am trying to type correctly following code:
interface SomeObject {
fn1: (params: { a: string, b: object }) => void,
fn2: (params: { c: number }) => number,
fn3: () => number
}
type Methods = keyof SomeObject;
let someObject: SomeObject = {
fn1: ({ a, b }) => console.log(a, b),
fn2: ({ c }) => c,
fn3: () => 1
}
const fn = <T extends Methods>({ method, parameters }: {
method: T,
parameters: Parameters<SomeObject[T]>
}) => {
const _method = someObject[method]
_method(parameters[0]);
}
fn({ method: 'fn1', parameters: [{a:'str', b:{}}] });
The problem that I encountered is that _method gets a following type:
const _method: (params: {
a: string;
b: object;
} & {
c: number;
}) => number | void
So it takes an intersection of all possible parameters and thus making it impossible to use the fn({ method, parameters }) notation. Is there any workaround? (without using as or any)
You can find TypeScript playground here.