Issue
I'm trying to type useState() hook which can get number and string type as its value.
export interface Select {
selectValue: React.Dispatch<React.SetStateAction<number | string>>;
...
}
And I'm trying to use above component like this,
const [value, setValue] = React.useState(0);
<Select selectValue = {setValue} />
But It gives me this Error.
Type 'Dispatch<SetStateAction<number>>' is not assignable to type 'Dispatch<SetStateAction<string | number>>'.
Type 'SetStateAction<string | number>' is not assignable to type 'SetStateAction<number>'.
Type 'string' is not assignable to type 'SetStateAction<number>'.
How can I resolve this Error?
Solution
You just need to provide a generic type argument to useState<T>
like this:
const [value, setValue] = useState<string | number>(0);
Otherwise, it will infer the type from your initial value 0
which is only number
. Here's a complete example:
import {
default as React,
Dispatch,
ReactElement,
SetStateAction,
useState,
} from 'react';
interface SelectProps {
selectValue: string | number;
setSelectValue: Dispatch<SetStateAction<string | number>>;
}
declare function Select (props: SelectProps): ReactElement;
function Example (): ReactElement {
const [value, setValue] = useState<string | number>(0);
return <Select selectValue={value} setSelectValue={setValue} />;
}
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.