首页 > 解决方案 > 打字稿只复制函数参数而不是返回类型

问题描述

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

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

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

const bar = (...args) => { foo(...args); }

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

const bar: typeof foo = (...args) => { foo(...args); }

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

标签: typescript

解决方案


有内置的参数类型

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 

推荐阅读