我在TypeScript中使用react-redux
钩子useSelector
。是否支持静态类型?现在,我必须使用as
关键字进行投射。
interface User { age: number }
const selectUser = (state): User => state.user.detail
const MyComponent = () => {
const user1 = useSelector(selectUser)
user1.age = 'This is not number.' // No warning or error.
const user2 = useSelector<User>(selectUser)
user2.age = 'This is not number.' // No warning or error.
const user3 = useSelector(selectUser) as User
user3.age = 'This is not number.' // TS2339 error, but with casting.
}
答案 0 :(得分:0)
useSelector
有两个类型参数<TState, TSelected>
,第二个参数是所选值的类型。这样就可以了:
const user = useSelector<TState, User>(selectUser)