使用TypeScript的React-redux钩子

时间:2019-06-18 09:28:23

标签: typescript generics redux react-redux

我在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.

}

1 个答案:

答案 0 :(得分:0)

useSelector有两个类型参数<TState, TSelected>,第二个参数是所选值的类型。这样就可以了:

const user = useSelector<TState, User>(selectUser)