英文:
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) => isGoodFit(off));
When initialized the two variables above, I get a Typescript error that says 'availableOfferings' is possibly 'undefined'
.
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) => isGoodFit(off))
: undefined;
Here is how the data is being pulled with 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}
/>
);
}
答案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) => 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论