如何制作函数的参数'类型遵循另一个函数的参数'

发布于 2025-02-10 18:37:26 字数 460 浏览 2 评论 0原文

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);
});

如上所述,在打字稿中,如何定义overwrite()定义的类型以使 newfunc 的参数遵循 oinderfunc 的参数。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

屋顶上的小猫咪 2025-02-17 18:37:26

使用仿制药来定义两个参数共享的函数类型

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文