Issue
Say I have a parent component with two child components:
const Parent = () => {
const [myVar, setmyVar] = useState(false)
return (
<>
<MyChildComponent1 myVar={myVar} setMyVar={setMyVar} \>
<MyChildComponent2 myVar={myVar} \>
</>
)
}
Now how would I go about setting the type correctly in MyChildComponent2
?
This is what I've come up with so far:
const MyChildComponent1 = (
{myVar, setMyVar}:
{myVar: boolean, setMyVar: (value: boolean) => void}) = (...)
Is the type for setMyvar
correct? Or should it be something else?
Solution
The type that would match the function returned from invoking useState
would be:
setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void;
If we look at the type definition file from DefinitelyTyped
[1], we can see that the second type in the return type is a dispatch:
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Thus the generic type provided is passed through to SetStateAction<S>
, which is defined as:
type SetStateAction<S> = S | ((prevState: S) => S);
So essentially, an interface for your component would be the following:
interface IProps {
myVar: boolean;
setMyVar?: (value: boolean | (prevVar: boolean) => boolean) => void;
}
As @Retsam said, it's best to use React's exported types:
import { Dispatch, SetStateAction } from "react";
interface IProps {
myVar: boolean;
setMyVar?: Dispatch<SetStateAction<boolean>>;
}
References: [1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845
Answered By - ljbc1994
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.