Typescript(类型'undefined'不能分配给类型)为什么我的数组有一个|号?未定义?

里昂·加班

我有一个称为combinedMarkets5或3个不同市场阵列的组合的阵列。所有这些数组都具有以下接口IMarketAsset[]

export interface IMarketAsset {
  exchange: string;
  base: string;
  quote: string;
  price_quote: string;
  timestamp: string;
}

这是打字稿错误发生的地方:

const combinedMarkets = asset !== 'BTC' && asset !== 'ETH' ?
  btcMarkets.concat(ethMarkets).concat(marketUSD).concat(marketUSDC).concat(marketUSDT) :
  marketUSD.concat(marketUSDC).concat(marketUSDT);

const filteredMarkets = combinedMarkets.length > 0 ? filterByUSDbase(asset, combinedMarkets) : [];

类型'({price_quote:string; exchange:string; base:string; quote:string; timestamp:string;} | undefined)[]'的参数不能分配给'IMarketAsset []'类型的参数。输入'{price_quote:string; 交换:字符串; base:字符串; quote:字符串; 时间戳:字符串;} | 未定义”不能分配给“ IMarketAsset”类型。类型'undefined'不能分配给类型'IMarketAsset'.ts(2345)

const combinedMarkets: ({
  price_quote: string;
  exchange: string;
  base: string;
  quote: string;
  timestamp: string;
} | undefined)[]

在此处输入图片说明

为什么CombinedMarkets是一个类型为IMarketAsset或未定义的对象的数组

完整的CombineExchangeData函数

// Filter by BTC, ETH, USD, USDT or USDC prices
// If asset has BTC/ETH pairing, obtain exchange BTC/ETH price to calculate assets USD/USDT value
export const combineExchangeData =
  (asset: string, { marketBTC, marketETH, marketUSD, marketUSDT, marketUSDC }: IGetMarketsRes) => {
    const btcBasedExchanges = marketBTC.filter((market: IMarketAsset) => market.base === asset);
    const ethBasedExchanges = marketETH.filter((market: IMarketAsset) => market.base === asset);
    const btcUSDTprices = marketUSDT.filter((market: IMarketAsset) => market.base === 'BTC');
    const btcUSDprices = marketUSD.filter((market: IMarketAsset) => market.base === 'BTC');
    const ethUSDTprices = marketUSDT.filter((market: IMarketAsset) => market.base === 'ETH');
    const ethUSDprices = marketUSD.filter((market: IMarketAsset) => market.base === 'ETH');

    const btcPricedMarkets = filterByExchangeBase(btcBasedExchanges, btcUSDTprices, btcUSDprices);
    const ethPricedMarkets = filterByExchangeBase(ethBasedExchanges, ethUSDTprices, ethUSDprices);

    const btcMarkets = btcPricedMarkets.filter((market) => R.not(R.isNil(market)));
    const ethMarkets = ethPricedMarkets.filter((market) => R.not(R.isNil(market)));

    const combinedMarkets = asset !== 'BTC' && asset !== 'ETH' ?
      btcMarkets.concat(ethMarkets).concat(marketUSD).concat(marketUSDC).concat(marketUSDT) :
      marketUSD.concat(marketUSDC).concat(marketUSDT);

    console.log('combinedMarkets', combinedMarkets);
    const filteredMarkets = combinedMarkets.length > 0 ? filterByUSDbase(asset, combinedMarkets) : [];
    console.log('filteredMarkets', filteredMarkets);

    if (R.isEmpty(filteredMarkets)) return [];

    return filteredMarkets.map((market: IMarketAsset) => {
      if (market) {
        return {
          ...market,
          price_quote: formatPrice(market.price_quote)
        }
      }
    });
  };

有用的功能

这是我在主函数中使用的其他2个util函数。我也将问题缩小到btcMarketsandethMarkets数组。所以看着filterByExchangeBase

import * as R from 'ramda'

import { USD_CURRENCIES } from '../shared/constants/api'
import { IMarketAsset } from '../shared/types'

const calculateBasePrice = (assetBtcPrice: string | number, btcPrice: string | number) => 
  (Number(assetBtcPrice) * Number(btcPrice)).toString();

export const filterByExchangeBase =
  (exchanges: IMarketAsset[], usdtExchanges: IMarketAsset[], usdExchanges: IMarketAsset[]) =>
    exchanges.map((exchange) => {
      let basePriced = usdtExchanges.filter((btcExchange) => btcExchange.exchange === exchange.exchange)[0];

      if (!basePriced) {
        basePriced = usdExchanges.filter((btcExchange) => btcExchange.exchange === exchange.exchange)[0];
      }

      if (basePriced) {
        const { price_quote: assetBtcPrice } = exchange;
        const { price_quote: btcPrice } = basePriced;

        return {
          ...exchange,
          price_quote: calculateBasePrice(assetBtcPrice, btcPrice)
        }
      }
    });

export const filterByUSDbase = (asset: string, combinedMarkets: IMarketAsset[] | undefined) => {
  if (!combinedMarkets) return [];
  return R.not(R.any(R.equals(asset))(USD_CURRENCIES))
    ? combinedMarkets.filter((marketAsset: IMarketAsset) => {
      if (marketAsset && marketAsset.base) {
        return marketAsset.base === asset;
      }
    }) : [];
}
里昂·加班

问题是,在我的filterByExchangeBaseutil函数中,我使用.map而不是.filter它将导致undefined该数组中的某些对象。切换到过滤器可确保只有现有项目才能将其放入数组。

...

更新:通过将.map更改为.filter,price_quote更新没有进行

重构逻辑以确保如果btcMarkets和ethMarkets为空,则不使用它们。

export const combineExchangeData =
  (asset: string, { marketBTC, marketETH, marketUSD, marketUSDT, marketUSDC }: IGetMarketsRes) => {
    const btcBasedExchanges = marketBTC.filter((market: IMarketAsset) => market.base === asset);
    const ethBasedExchanges = marketETH.filter((market: IMarketAsset) => market.base === asset);
    const btcUSDTprices = marketUSDT.filter((market: IMarketAsset) => market.base === 'BTC');
    const btcUSDprices = marketUSD.filter((market: IMarketAsset) => market.base === 'BTC');
    const ethUSDTprices = marketUSDT.filter((market: IMarketAsset) => market.base === 'ETH');
    const ethUSDprices = marketUSD.filter((market: IMarketAsset) => market.base === 'ETH');

    const btcPricedMarkets = notBTCorETH(asset) ? filterCryptoBase(btcBasedExchanges, btcUSDTprices, btcUSDprices) : [];
    const ethPricedMarkets = notBTCorETH(asset) ? filterCryptoBase(ethBasedExchanges, ethUSDTprices, ethUSDprices) : [];

    const btcMarkets = R.not(R.isEmpty(btcPricedMarkets)) ? btcPricedMarkets.filter((market: IMarketAsset) => R.not(R.isNil(market))) : [];
    const ethMarkets = R.not(R.isEmpty(ethPricedMarkets)) ? ethPricedMarkets.filter((market: IMarketAsset) => R.not(R.isNil(market))) : [];

    const combinedMarkets = notBTCorETH(asset) ?
      btcMarkets.concat(ethMarkets).concat(marketUSD).concat(marketUSDC).concat(marketUSDT) :
      marketUSD.concat(marketUSDC).concat(marketUSDT);

    const filteredMarkets = filterByUSDbase(asset, combinedMarkets);

    if (R.isEmpty(filteredMarkets)) return [];

    return filteredMarkets.map((market: IMarketAsset) => ({
      ...market,
      price_quote: formatPrice(market.price_quote)
    }));
  };

export const filterCryptoBase =
  (exchanges: IMarketAsset[] | any, usdtExchanges: IMarketAsset[], usdExchanges: IMarketAsset[]) => {
    return exchanges.map((exchange: IMarketAsset) => {
      let basePriced = usdtExchanges.filter((btcExchange) => btcExchange.exchange === exchange.exchange)[0];
      if (!basePriced) {
        basePriced = usdExchanges.filter((btcExchange) => btcExchange.exchange === exchange.exchange)[0];
      }

      if (exchange && basePriced && exchange.price_quote && basePriced.price_quote) {
        const { price_quote: assetBtcPrice } = exchange; // Asset price in BTC/ETH
        const { price_quote: usdPrice } = basePriced; // BTC/ETH price in USDT/USD
        const price_quote = calculateBasePrice(assetBtcPrice, usdPrice).toString();

        return {
          ...exchange,
          price_quote
        }
      }

      return null;
    });
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在TypeScript中,为什么可以将“ null”分配给类型“ undefined”的变量,反之亦然

TypeScript和Redux:为什么需要添加`| | undefined`到我的Reducer状态类型?

React&TypeScript HOC-为什么我无法将类型'{}'分配给类型P?

TypeScript-输入'number | 未定义”不能分配给“数字”类型

无法在构造函数定义中将类型“ undefined”分配给类型“ number”

类型'undefined'不能分配给'never'类型

Typescript:undefined的简写形式,而string是可选的属性类型?

类型'false'不能分配给类型'(((status:number)=> boolean)| undefined'TypeScript

输入'string | 编号| 空| undefined'不能分配给'null'类型

TypeScript:“数字| 未定义”不能分配给“数字”类型的参数

Typescript:类型'undefined'不能用作索引类型.ts(2538)

如何配置TypeScript来避免:类型'string'不能分配给类型'“ desc” | “ asc” | undefined'.ts(2322)?

输入'string | 不能将null分配给类型'string | TypeScript未定义的错误

JSX元素类型'ReactElement <any>不是JSX元素的构造函数。类型'undefined'不能分配给类型'Element | 空值'

Typescript-如何解决“类型'undefined'不能分配给类型'XXXX'”的问题?

提取:“字符串”类型的参数| 未定义”不能分配给“ RequestInfo”类型的参数

使用Angular Route Guard时:'Observable <true | undefined>'不能分配给类型>'Observable <boolean>'

Typescript-无法将“ undefined”类型分配给“ string | type” 编号| 符号'

TypeScript - 类型未定义不能分配给类型 ICustomType

TypeScript:'Card | 类型的参数 undefined' 不可分配给类型为 'Card' 的参数

Person 类型的 TypeScript 错误 (TS2345) 参数 | undefined 不能分配给 Person 类型的参数

如何修复错误类型 Item[] | undefined 不能使用 react 和 typescript 分配给 Item[] 类型?

类型 GQLSchema 不可分配给类型 undefined

“MonoTypeOperatorFunction<T>”类型的参数不能分配给“OperatorFunction<T>”类型的参数 未定义,T>'

即使在 .filter 函数删除 undefined 之后,Typescript 类型 (string | undefined ) 也不能分配给类型 string[]

类型 'string' 不可分配给类型 'WebkitAppearance | 在 React + TypeScript 中未定义?

循环遍历类型对象以检查未定义的属性并将其分配给具有相同字段的另一个类对象

“未定义”类型不能分配给“Promise<any>”类型的参数 | PromiseLike<承诺<任何>>

Angular TypeScript:“类型 '(string | undefined)[]' 不能分配给类型 'string[]'。”