How enforce a method call typechecking for dynamic methods

Viewed 31

Consider a use case:

// library method, I can't edit it. Its calling my custom methods
function dynamicMethod(action, params) {
    ....
    call1[action](params);
    ...
}

// my custom methods

function forHuman({first, last}: {first: string; last: string }) {
 ...
}
function forVehicle({brand, year}: {brand: string; year: number}) {
 ...
}

Using the libs I m calling it

dynamicMethod('forHuman', obj); // How to get compile time error here if obj is not matching with args of forHuman??
dynamicMethod('forVehicle', obj); // How to get compile time error here if obj is not matching with args of forVehicle??
1 Answers

This work for me


interface Human {
  first: string,
  last: string
}
interface Vehicle { brand: string; year: number }
function forHuman ({ first, last }: Human) {

}
function forVehicle ({ brand, year }: Vehicle) {

}

interface Funs {
  forHuman: (arg: Human) => void
  forVehicle: (arg: Vehicle) => void
}
const call1 = { forHuman, forVehicle }

function dynamicMethod<K extends keyof Funs> (action: K, ...arg: Parameters<Funs[K]>) {
  // ...
  (call1[action] as (...arg: Parameters<Funs[K]>) => ReturnType<Funs[K]>)(...arg)
  // ...
}
Related