If I have this code:
import { useState } from "preact/hooks";
export default function Test() {
const [state, setState] = useState(null);
setState('string');
}
Then I get this error:
Argument of type 'string' is not assignable to parameter of type '(prevState: null) => null'.deno-ts(2345)
I understand that it expects me to use the same value type of the initial type. However if the initial value is an actual literal like number:
- const [state, setState] = useState(null);
+ const [state, setState] = useState(1);
Then the error is:
Argument of type 'string' is not assignable to parameter of type 'number | ((prevState: number) => number)'.deno-ts(2345)
Reading What is prevState in ReactJS? or Hooks – Preact Guide doesn’t help me understand:
- What does
((prevState: null) => null) | nullmean? - Why is the first case the required type not
null | ((prevState: null) => null)? - How can I use multiple type? For example, the initial value is 1 or null, but I then set the value to
'string'afterward?
>Solution :
((prevState: null) => null) | null means you can call the state setter function with an updater callback (where the previous state is null and the returned value of the callback is also null) or you can pass it null directly.
Example: setState(null) or setState((prev) => null).
The order of these two options in the type definition is unimportant.
To allow more than one type to be held in that state, you need to be explicit in your definition. Without passing a type, the type will be inferred by the initial value. Your initial value is null so the inferred type is null and nothing else.
To allow a string or null, you can use const [state, setState] = useState<null | string>(null);
The resulting type definition would be (at least close to) ((prevState: null | string) => null | string) | null | string