3

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
  • Remember that the react-redux hooks are still in alpha phase. Commented Jun 18, 2019 at 9:36

1 Answer 1

1

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

const user = useSelector<TState, User>(selectUser)
Sign up to request clarification or add additional context in comments.

2 Comments

What is TState?
TState should be type of state of whole store.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.