【问题标题】:Typescript, function with 2 types of params and returns: Cannot invoke an expression whose type lacks a call signature打字稿,具有 2 种参数类型的函数并返回:无法调用类型缺少调用签名的表达式
【发布时间】:2019-07-09 23:38:59
【问题描述】:

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

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

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

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

无法调用类型缺少调用签名的表达式。类型 '{ (callbackfn: (value: IResAssetPrice, index: number, array: IResAssetPrice[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: 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】:

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

    TypeScript 支持结构类型(也称为鸭子类型),这意味着类型在共享相同成员时是兼容的。您的问题是 Apple 和 Pear 不共享所有成员,这意味着它们不兼容。然而,它们与仅具有 isDecayed: 布尔成员的另一种类型兼容。由于结构类型,您不需要从这样的接口继承 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;
        }
      });
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2017-09-01
      • 2017-12-19
      • 2021-02-06
      • 2017-07-14
      • 2017-03-17
      相关资源
      最近更新 更多