如何处理Typescript中的数组“可能未定义”错误

huangapple go评论66阅读模式
英文:

How to account for array "is possibly undefined" error in Typescript

问题

我有一个名为availableOfferings的数组,它在API调用完成后设置。

const { offerings: availableOfferings } = useGetOfferings();

然后,我有两个变量依赖于availableOfferings中的数据。

const bestOffering = availableOfferings[0];

const relevantOfferings = availableOfferings
    .slice(1)
    .filter((off: any) => isGoodFit(off));

在初始化上述两个变量时,我会收到一个TypeScript错误,该错误显示'availableOfferings'可能为'undefined'。

解决此问题的最佳方法是什么?

我尝试了以下方法,它有效,但看起来不够优雅:

const bestOffering = availableOfferings ? availableOfferings[0] : undefined;

const relevantOfferings = availableOfferings
  ? availableOfferings.slice(1).filter((off: any) => isGoodFit(off))
  : undefined;

以下是如何使用useGetOfferings提取数据的方式:

export const OfferingsContext = createContext<{
  [x: string]: any;
  offerings?: {
    [x: string]: any;
  };
}>({
  offerings: {},
});

export function useGetOfferings() {
  return useContext(OfferingsContext);
}
function OfferingsProvider({ children }: Props) {
  const [offerings, setOfferings] = useState([]);
  const [hasGoodFits, setHasGoodFits] = useState(undefined);
  const { getAccessTokenSilently } = useAuth0();
  const fetchData = async () => {
    try {
      const responseOfferings = await BusinessApi.getOfferings(
        getAccessTokenSilently
      );
      const hasGoodFitsResult = responseOfferings.data.data.some(
        (offering: any) => isGoodFit(offering)
      );
      setOfferings(responseOfferings.data.data);
      setHasGoodFits(hasGoodFitsResult);
      return { responseOfferings, hasGoodFitsResult };
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <OfferingsContext.Provider
      value={{ offerings, fetchData, hasGoodFits }}
      children={children}
    />
  );
}
英文:

I have an array called availableOfferings that gets set after an API call is completed.

const { offerings: availableOfferings } = useGetOfferings();

Then, I have two variables that rely on the data contained in availableOfferings

const bestOffering = availableOfferings[0];

const relevantOfferings = availableOfferings
    .slice(1)
    .filter((off: any) =&gt; isGoodFit(off));

When initialized the two variables above, I get a Typescript error that says &#39;availableOfferings&#39; is possibly &#39;undefined&#39;.

What is the best way to resolve this issue?

I tried this and it worked but doesn't look too elegant:

const bestOffering = availableOfferings ? availableOfferings[0] : undefined;

const relevantOfferings = availableOfferings
  ? availableOfferings.slice(1).filter((off: any) =&gt; isGoodFit(off))
  : undefined;

Here is how the data is being pulled with useGetOfferings:

export const OfferingsContext = createContext&lt;{
  [x: string]: any;
  offerings?: {
    [x: string]: any;
  };
}&gt;({
  offerings: {},
});

export function useGetOfferings() {
  return useContext(OfferingsContext);
}
function OfferingsProvider({ children }: Props) {
  const [offerings, setOfferings] = useState([]);
  const [hasGoodFits, setHasGoodFits] = useState(undefined);
  const { getAccessTokenSilently } = useAuth0();
  const fetchData = async () =&gt; {
    try {
      const responseOfferings = await BusinessApi.getOfferings(
        getAccessTokenSilently
      );
      const hasGoodFitsResult = responseOfferings.data.data.some(
        (offering: any) =&gt; isGoodFit(offering)
      );
      setOfferings(responseOfferings.data.data);
      setHasGoodFits(hasGoodFitsResult);
      return { responseOfferings, hasGoodFitsResult };
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() =&gt; {
    fetchData();
  }, []);


  return (
    &lt;OfferingsContext.Provider
      value={{ offerings, fetchData, hasGoodFits }}
      children={children}
    /&gt;
  );
}

答案1

得分: 2

这就是 可选链操作符 ?.空值合并操作符 ?? 发挥作用的时候:

const bestOffering = availableOfferings?.[0];

const relevantOfferings = (availableOfferings ?? [])
    .slice(1)
    .filter((off: any) => isGoodFit(off));
英文:

That's when optional chaining ?. and nullish coalescing operator ?? comes into handy:

const bestOffering = availableOfferings?.[0];

const relevantOfferings = (availableOfferings ?? [])
    .slice(1)
    .filter((off: any) =&gt; isGoodFit(off));

答案2

得分: 1

你可以给availableOfferings设置一个默认值[],这样它总是有一个备用值 => 警告会消失。

const { offerings: availableOfferings = [] } = useGetOfferings()

但我不确定为什么你要将offerings声明为object类型,而不是array类型(在OfferingsContext中)。

英文:

You can give the availableOfferings a default value as [], so it always has a fallback value => the warning will be gone.

const { offerings: availableOfferings = [] } = useGetOfferings()

But I'm not sure why you declare your offerings with type object instead of type array (in OfferingsContext).

huangapple
  • 本文由 发表于 2023年2月6日 08:10:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定