簡體   English   中英

傳遞給另一個函數時,如何在Typescript中設置函數的類型?

[英]How to set the Type of a function in Typescript, when passing that into another function?

這是我的功能:

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;

但是也得到這個錯誤:

調用其類型缺少調用簽名的表達式

在此處輸入圖片說明

您用於聲明功能簽名接口的語法不太正確。 它看起來應該像這樣:

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

或者您可以使用類型別名

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

無論哪種情況,您都可以在其他地方將此類型用作道具:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM