我得到了下面的代码,它工作得很好,做我想做的,但是如果我将if条件移动到变量下,typescript开始警告我fakeTradeInfo
和fundsWeight
可能是未定义的。
// type of fundsWeight : SomeRandomArray[] | undefined
// type of fakeTradeInfo : SomeRandomObject | null
const StackOverflow = ({ row }: { row: INewTradeState }) => {
const fundsWeight = useSelector((state: RootState) => state.fakeFund.fundsWeight[row.univers.uniqueid]);
const fakeTradeInfo = useSelector((state: RootState) => getFakeTradesInfoById(state)(row.id));
if (fundsWeight && fakeTradeInfo) { // Work fine
return (
<>
<TextField variant="outlined" label="ccy" value={fakeTradeInfo.ccy} /> // Typescript doesn't warn about anything, work as expected
<TextField variant="outlined" label="fx" value={fakeTradeInfo.fx} />
{fundsWeight.map((fund) => (
<>Do Stuff</>
))}
</>
);
}
return <>not loaded</>;
};
这里的"not working"&;代码:
const StackOverflow = ({ row }: { row: INewTradeState }) => {
const fundsWeight = useSelector((state: RootState) => state.fakeFund.fundsWeight[row.univers.uniqueid]);
const fakeTradeInfo = useSelector((state: RootState) => getFakeTradesInfoById(state)(row.id));
const hasLoaded = fundsWeight && fakeTradeInfo;
if (hasLoaded) {
return (
<>
<TextField variant="outlined" label="ccy" value={fakeTradeInfo.ccy} /> // <=== HERE typescript warn about the probability that fakeTradeInfo may be undefined
<TextField variant="outlined" label="fx" value={fakeTradeInfo.fx} />
{fundsWeight.map((fund) => ( // <=== SAME HERE
<>Do Stuff</>
))}
</>
);
}
return <>not loaded</>;
};
如何使typescript知道hasLoaded意味着fakeTradeInfo/fundsWeight不能是undefined/null ?我想避免使用fakeTradeInfo!ccy语法。
您需要在实际使用它之前检查它是否未定义:
<TextField variant="outlined" label="ccy" value={fakeTradeInfo && fakeTradeInfo.ccy} />
或者使用可选的链接
<TextField variant="outlined" label="ccy" value={fakeTradeInfo?.ccy} />