打字稿只复制函数参数而不是返回类型

Mar*_*ahn 5 typescript

我有一些 util 方法,我想知道是否有办法将参数从一种方法复制到另一种方法。我正在玩弄typeof并尝试以这种方式键入第二个函数,但我无法弄清楚。

declare function foo(a: number, b: string): number;
Run Code Online (Sandbox Code Playgroud)

现在我想要一个类型barfoo's 参数,但不是返回类型,例如假设它调用 foo 但不返回任何内容:

const bar = (...args) => { foo(...args); }
Run Code Online (Sandbox Code Playgroud)

现在我可以声明bar具有与以下完全相同的类型foo

const bar: typeof foo = (...args) => { foo(...args); }
Run Code Online (Sandbox Code Playgroud)

但现在返回类型不匹配。那么我该怎么做:

  • 只需复制参数签名
  • 更改我从中获得的返回类型 typeof foo

art*_*tem 11

有内置参数类型

declare function foo(a: number, b: string): number;

type fooParameters = Parameters<typeof foo>;

declare const bar: (...parameters: fooParameters) => void;
// inferred as const bar: (a: number, b: string) => void 
Run Code Online (Sandbox Code Playgroud)