React-redux hooks with TypeScript

Viewed 2938

I am using react-redux hook useSelector with TypeScript. Is there any support for static typing? Now I have to cast using as keyword.

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 Answers

useSelector has two type parameters <TState, TSelected>, second parameter is type of selected value. So this is working:

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