2

I'm using React Typescript and I have the following warning:

warning Missing return type on function

This is my code:

 useEffect(() => {
    window.addEventListener('scroll', fetchAllFriends, { once: true })

    return () => {
      window.removeEventListener('scroll', fetchAllFriends)
    }
  }, [fetchAllFriends])

Does that mean that we need a return (): void on every cleanup function inside useEffect?

1
  • 3
    It means that your linter has a rule that you disagree with. As I likewise disagree with that rule, I would turn the rule off, but it is your call. Commented May 22, 2020 at 4:30

1 Answer 1

2

The reason why the above warning is happening is probably because you have activated following ESLint rule:

@typescript-eslint/explicit-function-return-type

To answer your question, you can set the return type as void.

Alternatively, you can turn the above rule off, as you don't always have to explicitly set the return type of all of your methods as TypeScript can usually infer the return types based on what is returned on the method. Personally, I turn it off for most of my projects.

getUser() {
  return service.getUser();
}

For instance, with the above scenario, TypeScript should be able to infer the return type without the need the specify the return type.


EDIT: as mentioned by @paolostyle in the comments, if you wish to keep the rule, but disable the rule for your scenario, you can toggle the allowExpressions option and set it to true.

"@typescript-eslint/explicit-function-return-type": ["error", {
  "allowExpressions": true,
}]
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you could also add allowExpressions: true to that rule config. That will disable this rule for inline anonymous functions, like the cleanup function in useEffect. However I'm personally not a fan of this rule and I'd suggest disabling it altogether.
Ahh..! Good tip. I have never explored that option as I always turn off that rule 🤣

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.