1

I developed a react typescript application with react 16.9 and typescript 3.5.2. It uses react state hooks like

const [hValue, setHValue] = useState();

type of the hValue is IValue

So the setHValue has return type React.Dispatch<any>

Then I updated the typescript version to 3.9.7 and it gives compilation errors and it seems that now the return type of setHValue has changed to React.Dispatch<React.SetStateAction<undefined>>

Why is that? and how to resolve this issue?

2
  • what's the type of hValue? Commented Sep 17, 2020 at 4:50
  • IValue I edited the questions and included that Commented Sep 17, 2020 at 4:57

1 Answer 1

2

Let's have a look at the type of useState

    function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];

It is to say, if you didn't specify any S, it will be undefined by default.

So you will need to specify your initial type, say if hValue is a number, you can do

const [hValue, setHValue] = useState<number>();

In this way, setValue will be React.Dispatch<SetStateAction<number>> type

Sign up to request clarification or add additional context in comments.

1 Comment

In above example setValue will be setHaValue: React.Dispatch<React.SetStateAction<number | undefined>> type

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.