To ensure the function parameters in a class stay synced, you can utilize overloads or leverage conditional types to extract specific methods and parameter types. By using a generic type argument in the function, you can establish the relationship between the method and data parameter:
type AppleData = { apple: number }
type OrangeData = { orange: number }
type BananaData = { banana: number }
class MyClass {
apple(data: AppleData) {
//Do Something
}
orange(data: OrangeData) {
//Do Something
}
banana(data: BananaData) {
//Do Something
}
}
type KeyOfType<T, V> = {
[P in keyof T] : T[P] extends V? P: never
}[keyof T]
type Data<T, K extends PropertyKey> = T extends Record<K, (data: infer D) => void> ? D : never;
const search = <K extends KeyOfType<MyClass, (a: any) => any>>(method: K, data: Data<MyClass, K>) => {
//Perform common tasks
let myClass = new MyClass();
return myClass[method](data);
}
search("apple", { apple: 1 })
search("apple", { orange: 1}) // error
Play