Issue
I have a setState function in React that I would like to pass in to another function as a parameter. I was wondering how I can define this in TypeScript without using the "any" as the type:
So far it looks like this:
export const keyDownHandler = (
event: React.KeyboardEvent,
buttonDate: number,
setShowCalendar: any
): void => {
// stuff happening
setShowCalendar(false);
};
Solution
The type of a React state setter from useState
is React.Dispatch<React.SetStateAction<stateType>>
. In your case, it looks like the state type is boolean
, so:
export const keyDownHandler = (event: React.KeyboardEvent, buttonDate: number, setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>): void => {
// stuff happening
setShowCalendar(false);
};
You can see this in index.d.ts
in @types/react
, or in a decent IDE (VSCode for instance), you can see it by hovering your mouse over the state setter:
In VSCode, hovering over setShowCalendar
shows this popup:
const setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.