React-Redux useSelector with TypeScript
Mar 2, 2021
React- Redux 7.1 之後提供了 useSelector
的hook ,就不需要再使用 connect
和 mapStateToProps
。
但是如果直接使用在 TypeScript 的時侯,因為 useSelector
並不知道 reducer
的型別,所以會有錯誤提示 :
Property 'todos' does not exist on type 'DefaultRootState'.
我們需要手動在 reducer 增加型別給 useSelector
使用
type RootState = ReturnType<typeof reducers>
並且另外自訂 useSelector
hook,這樣每次使用原本 React-Redux 提供的 useSelector
才不會太冗長。