3

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);
};
2
  • Try Function? Commented Jan 20, 2021 at 10:35
  • type ShowCalendar= (boolen) => void export const keyDownHandler = (event: React.KeyboardEvent, buttonDate: number, setShowCalendar: ShowCalendar): void => { // stuff happening setShowCalendar(false) } Commented Jan 20, 2021 at 10:38

4 Answers 4

5

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:

Cursor over state setter showing popup with const setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>

In VSCode, hovering over setShowCalendar shows this popup:

const setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>

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

Comments

2

You could use the type definition like this.

setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>

Comments

0

I think the easiest solution would be (b: boolean) => void, but if you want the full type, you can use React.Dispatch<React.SetStateAction<boolean>>.

Comments

0

You can use a function type for this. For example, a function that takes a boolean and returns nothing would be something like:

const setShowCalendar = (value: boolean) => {
   ... 
   logic
   ...
}

setShowCalendar's type would be let setShowCalendar: (value: boolean) => void; The type looks almost like the function itself, except for the fact that the body is missing.

Look up the types you're consuming and replace it in the above example Type Declaration.

You can read more about this here: https://www.typescriptlang.org/docs/handbook/functions.html#function-types

1 Comment

React state setters aren't that simple.

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.