Reputation: 19
type Func = (...args: any) => any;
// I use overwrite() to re-define an existing function
function overwrite(originalFunc: Func, newFunc: Func) {
}
function demo(str: string, num: number) {
console.log(str, num);
}
// Re-define the demo() function
overwrite(demo, (str, num) {
console.log('new func', str, num);
demo(str, num);
});
As above, in TypeScript how to define the types in definition of overwrite() to make the newFunc's arguments follow the originalFunc's.
Upvotes: 1
Views: 45
Reputation: 32244
Use generics to define a function type that both parameters share
function overwrite<F extends Function>(originalFunc: F, newFunc: F) {}
function demo(str: string, num: number) {
console.log(str, num);
}
overwrite(demo, (a: string, b: number) => {}); // Fine
overwrite(demo, (a: number, b: string) => {}); // Error
Upvotes: 2