Leon Gaban
Leon Gaban

Reputation: 39018

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

enter image description here

Upvotes: 0

Views: 56

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52133

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

Upvotes: 1

Related Questions