DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #17

Image description

Typing Functions

We have an addListener function here:

const addListener = (onFocusChange: unknown) => {
  window.addEventListener("focus", () => {
    onFocusChange(true);
  });

  window.addEventListener("blur", () => {
    onFocusChange(false);
  });
}
Enter fullscreen mode Exit fullscreen mode

The type of onFocusChange that is passed in is currently unknown.

We want it to be a function that will take in a single boolean argument.

🌟 Solution: Specify the Type of a Function

We can declare a function type using this syntax:

(isFocused: boolean) => void
Enter fullscreen mode Exit fullscreen mode

The isFocused argument is a boolean, and we are returning void.

This syntax can be used inline like this:

const addListener = (onFocusChange: (isFocused: boolean) => void) => {
Enter fullscreen mode Exit fullscreen mode

Or it can be extracted to its own type like this:

type FocusListener = (isFocused: boolean) => void;

const addListener = (onFocusChange: FocusListener) => {
Enter fullscreen mode Exit fullscreen mode

The basic structure starts with the arguments and the return type, both of which can be whatever you want.

We can use undefined for the return type, but then our function has to actually return undefined.

For times when our function has no return value, we should use void.

Here is an example of adding an isGreat boolean as an additional argument:

type FocusListener = (isFocused: boolean, isGreat: boolean) => void;
Enter fullscreen mode Exit fullscreen mode

Then whenever we called the FocusListener we would have to include parameters for both:

const addListener = (onFocusChange: FocusListener) => {
  onFocusChange(true, true)
}
Enter fullscreen mode Exit fullscreen mode

We can also use function types in the same way we are used to using other types. Just be aware that your return types match appropriately.

const myFocusListener = (isFocused: boolean): void => {
  // TypeScript error that `{}` is unassignable to void
  return {}
}
Enter fullscreen mode Exit fullscreen mode

Most of the time, we are not going to need these types unless we are passing functions to other functions or declaring the type of the function.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)