Typescript,具有两种类型的params和return的函数:不能调用类型缺少调用签名的表达式

问题描述 投票:0回答:1

我有一个函数filterAssets,它可以采用2种不同的数组。以下是两种不同的数组类型:

export interface IResAssetPrice {
  currency: string;
  price: string;
}

export interface IResAssetSupply {
  currency: string;
  availableSupply: string;
}

进行一些过滤然后返回相同的数组。但是我收到以下错误:

无法调用类型缺少调用签名的表达式。输入'{(callbackfn :(值:IResAssetPrice,index:number,array:IResAssetPrice [])=> value是S,thisArg?:any):S []; (callbackfn :(值:IResAssetPrice,index:number,array:IResAssetPrice [])=> any,thisArg?:any):IResAssetPrice []; } | {...; }'没有兼容的电话签名.ts(2349)

export const filterAssets = (assets: IResAssetPrice[] | IResAssetSupply[]): any => {
  const filtered = assets.filter((asset) => {
    if (asset.availableSupply && asset.availableSupply !== null) {
      return asset;
    }
    if (asset.price && asset.price !== '') {
      return asset;
    }
  });

  return filtered;
};

我认为它与预期的返回类型有关,所以我也试过以下无济于事。

export const filterAssets = (assets: IResAssetPrice[] | IResAssetSupply[]): {
  currency: string;
  price: string;
} | {
  currency: string;
  availableSupply: string;
} => {
  const filtered = assets.filter((asset) => {
    if (asset.availableSupply && asset.availableSupply !== null) {
      return asset;
    }
    if (asset.price && asset.price !== '') {
      return asset;
    }
  });

  return filtered;
};
javascript typescript
1个回答
0
投票

啊刚刚在这里找到答案:Cannot invoke an expression whose type lacks a call signature

TypeScript支持结构类型(也称为duck typing),这意味着类型在共享相同成员时是兼容的。您的问题是Apple和Pear不会共享其所有成员,这意味着它们不兼容。但是它们与另一个只有isDecayed:boolean成员的类型兼容。由于结构类型的原因,您不需要从这样的界面继承Apple和Pear。

然后现在能够使用兼容当前接口的第3类修复我的问题:)

type AssetResponse = {
  currency: boolean;
  price?: string;
  availableSupply?: string;
};

export const filterAssets = (assets: AssetResponse[]) => {
  const filtered = assets.filter((asset) => {
    if (asset.availableSupply && asset.availableSupply !== null) {
      return asset;
    }
    if (asset.price && asset.price !== '') {
      return asset;
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.