JayceLin
JayceLin

Reputation: 19

How to make a function's arguments' types follow another function's arguments'

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

Answers (1)

Iain Shelvington
Iain Shelvington

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

Related Questions