Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function type as a parameter in TypeScript

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);
};
like image 936
rockon_d Avatar asked Dec 02 '25 06:12

rockon_d


2 Answers

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>>

like image 143
T.J. Crowder Avatar answered Dec 03 '25 20:12

T.J. Crowder


You could use the type definition like this.

setShowCalendar: React.Dispatch<React.SetStateAction<boolean>>
like image 38
Prateek Thapa Avatar answered Dec 03 '25 19:12

Prateek Thapa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!