【问题标题】:Typescript copying only function arguments and not return type打字稿只复制函数参数而不是返回类型
【发布时间】:2019-03-28 06:30:06
【问题描述】:

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

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

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

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

现在我可以声明barfoo 具有完全相同的类型:

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

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

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

    有内置的Parameters类型

    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 
    

    【讨论】:

    • 在我的情况下,我只想要第一个参数,为此您可以执行Parameters&lt;typeof foo&gt;[0]。最后Parameters&lt;&gt;返回一个元组。
    猜你喜欢
    • 2019-07-16
    • 2022-01-12
    • 2015-08-10
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多