【问题标题】:How to set the Type of a function in Typescript, when passing that into another function?将 Typescript 中的函数传递给另一个函数时,如何设置函数的类型?
【发布时间】:2018-09-25 14:01:21
【问题描述】:

这是我的功能:

const payout = (asset: ILPAsset, type: string)
    => type === 'daily' ? asset.lastPayout : asset.historical;

我在哪里使用它:

@bind
private mapDailyAssets(payoutType: string, payout: payoutFunc, assets: ILPAsset[], currency: string) {
  return assets.map((asset) => (
    <div className={b('table-row')()} key={asset.symbol}>
      <div>{asset.symbol}</div>
      <div className={b('asset-value')()}>{formatMoney(payout(asset, payoutType), currency)}</div>
    </div>
  ));
}

我在尝试为类型 payoutFunc 设置 interface 时遇到错误:

interface payoutFunc: (asset: ILPAsset, type: string) => string;

但也出现此错误:

调用类型缺少调用签名的表达式

【问题讨论】:

    标签: javascript reactjs function typescript


    【解决方案1】:

    您声明函数签名接口的语法不太正确。它应该是这样的:

    interface payoutFunc { 
      (asset: ILPAsset, type: string): string;
    }
    

    或者你可以使用type alias:

    type payoutFunc = (asset: ILPAsset, type: string) => string;
    

    无论哪种情况,您都可以将此类型用作其他地方的道具:

    interface MyProps {
      foo: string;
      bar: number;
      payout: payoutFunc;
    }
    

    【讨论】:

    • 谢谢!这正是我所需要的,堆栈上的其他问题只是涵盖了函数本身,并不是在寻找 Typescript 函数类型语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2018-07-02
    • 2011-10-31
    • 1970-01-01
    • 2019-07-25
    相关资源
    最近更新 更多