我正在從 javascript 轉向 typescript,這是我多次遇到的錯誤:在一個組件中,我正在等待獲取以返回一個對象,直到那個時候,該組件才返回 null。如果對象在那里,我將渲染對象的一些屬性:const Component = () => { const [user, setUser] = useState(null) useEffect(() => { getUser().then(setUser) }, [getUser]) if (!user) return null return ( <ul> <li>{`Username: ${user.userName}`}</li> <li>{`Email: ${user.email}`}</li> </ul> )}打字稿然后拋出一個錯誤Object is possibly 'null'. TS2531對于更一般的情況,這個問題在這里已經有了答案: How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?但是,確保對象永遠不會為 null 感覺不對。我的意思是,我可以初始化對象;const [user, setUser] = useState({ userName: 'UNKNOWN', email: 'UNKNOWN' })但這顯然也不是我的最佳解決方案。我很失望打字稿無法識別用戶在到達 JSX 時永遠不能為 null。但這可能是因為我正在考慮天真的方式。仍然是問題 -我如何處理打字稿組件中的這種典型情況?
如何在 Typescript 中處理等待獲取的對象
慕雪6442864
2023-03-24 14:21:14