简体   繁体   中英

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

Here is my function:

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

And where I'm using it:

@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>
  ));
}

I'm getting errors when trying to set an interface for type payoutFunc :

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

But also getting this error:

invoke an expression whose type lacks a call signature

在此处输入图片说明

Your syntax for declaring a function signature interface is not quite right. It should look like this:

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

Or you could use a type alias :

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

In either case you can use this type as a prop somewhere else:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM