typescript 函数缺少结束返回语句,返回类型不包括“undefined”

7tofc5zh  于 2023-06-07  发布在  TypeScript
关注(0)|答案(4)|浏览(594)

函数缺少结束返回语句,并且返回类型不包括“未定义”。
在下面的async await函数中,我的返回类型为Promise: <any>,但我想纠正它,所以我做了以下操作:

export const getMarkets = async (): Promise<IGetMarketsRes> => {
  try {
    const nomicsUSD = prepHeaders('USD');
    const marketUSD = await nomicsUSD.get(exchangeMarketPrices);
    const nomicsUSDC = prepHeaders('USDC');
    const marketUSDC = await nomicsUSDC.get(exchangeMarketPrices);
    const nomicsUSDT = prepHeaders('USDT');
    const marketUSDT = await nomicsUSDT.get(exchangeMarketPrices);

    console.log('marketUSD', marketUSD);

    return {
      marketUSD: marketUSD.data,
      marketUSDC: marketUSDC.data,
      marketUSDT: marketUSDT.data
    }
  } catch (err) {
    console.error(err);
  }
}

这就造成了上面的错误。

其中getMarkets被称为:

export const fetchMarketPrices = (asset: string) => (dispatch: any) => {
  dispatch(actionGetMarketPrices);
  return getMarkets().then((res) => {
    const { marketUSD, marketUSDC, marketUSDT } = res;
    const combinedExchanges = marketUSD.concat(marketUSDC).concat(marketUSDT);
    const exchangesForAsset = combinedExchanges.filter((marketAsset: IMarketAsset) =>
      marketAsset.base === asset);
    return dispatch(actionSetMarketPrices(exchangesForAsset));
  });
}

**Promise<>语法的正确类型是什么?

我也尝试了这个,我希望这是正确的方式,但得到了一个缺少的Promise返回,但这是一个异步await函数,这就是为什么返回在try语句中:
export const getMarkets = async (): Promise<IGetMarketsRes> => {

yyyllmsg

yyyllmsg1#

最好的解决方案是在catch上抛出错误,而不是取消定义返回类型。undefined类型删除了使用TypeScript的全部要点。
试试这个:

export const getMarkets = async (): Promise<IGetMarketsRes> => {
  try {
     // Your code :)
  } catch (err) {
    // Throw error
    throw(err)
  }
}
mw3dktmi

mw3dktmi2#

保留try catch的解决方案

export const getMarkets = async (): Promise<IGetMarketsRes | undefined> => {
  try {
    const nomicsUSD = prepHeaders('111');
    const marketUSD = await nomicsUSD.get(exchangeMarketPrices);
    const nomicsUSDC = prepHeaders('222');
    const marketUSDC = await nomicsUSDC.get(exchangeMarketPrices);
    const nomicsUSDT = prepHeaders('333');
    const marketUSDT = await nomicsUSDT.get(exchangeMarketPrices);

    const { data: dataUSD } = marketUSD;
    const { data: dataUSDC } = marketUSDC;
    const { data: dataUSDT } = marketUSDT;

    if (R.isEmpty(dataUSD) || R.isEmpty(dataUSDC) || R.isEmpty(dataUSDT)) {
      console.error('Market data unavailable');
    }

    return {
      marketUSD: marketUSD.data,
      marketUSDC: marketUSDC.data,
      marketUSDT: marketUSDT.data
    }
  } catch (error) {
    console.error(error);
  }
}

一个更好的DRY示例

https://codereview.stackexchange.com/questions/213909/get-an-array-of-currency-exchange-prices-based-on-asset

export const fetchMarket = async (currency: string): Promise<any> => {
  try {
    const request = prepHeaders(currency);
    const response =  await request.get(EXCHANGE_MARKET_PRICES);
    if (!response) {
      throw new Error('USD Markets unavailable.');
    }
    return response.data;
  }
  catch(err) {
    console.error(err);
  }
}

// GET Market prices
// http://docs.nomics.com/#operation/getMarkets
export const getMarkets = async (): Promise<IGetMarketsRes | undefined> => {
  try {
    const markets: IMarketRes = {};

    for (let currency of BASE_CURRENCIES) {
      const key = 'market' + currency;
      markets[key] = await fetchMarket(currency);
    }

    return {
      marketUSD: markets['marketUSD'],
      marketUSDC: markets['marketUSDC'],
      marketUSDT: markets['marketUSDT'],
    }
  } catch (error) {
    console.error(error);
  }
}

以及来自actions文件的调用:

// Fetch USD, USDC & USDT markets to filter out Exchange List.
export const fetchMarketPrices = (asset: string) => (dispatch: any) => {
  dispatch(actionGetMarketPrices);
  return getMarkets().then((res) => {
    if (res) {
      const exchangesForAsset = combineExchangeData(asset, res);
      return dispatch(actionSetMarketPrices(exchangesForAsset));
    }
  });
}
ne5o7dgx

ne5o7dgx3#

如果出现错误,代码将隐式返回undefined,因为您捕获了error而没有重新抛出它。
我猜您的tsconfig.json文件将noImplicitReturns设置为true。如果将其更改为false,则编译器错误将不再显示。但是,我建议将noImplicitReturns设置为true,并在catch子句中重新抛出错误。
您还可以在catch块中返回默认的IGetMarketsRes,如果它与您的应用程序逻辑一起工作的话。我制作了一个视频,向您展示了处理错误TS2366的不同可能性:https://www.youtube.com/watch?v=8N_P-l5Kukk&t=363s

sg2wtvxw

sg2wtvxw4#

你需要在catch中抛出错误,这将解决问题。像这样

catch (error) {
    console.log(error);
    throw new Error("Something is Wrong!")
}

相关问题