![](/img/trans.png)
[英]How can I specify a TypeScript type when passing an object into a function?
[英]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.