Home > database >  How to dry up type definition of function that returns another function
How to dry up type definition of function that returns another function

Time:06-24

I've enabled the ESLint rule that forces you to specify all functions' return types. In React hooks, this leads to patterns such as the following:

const useSubmitForm = (): ((
  form: FormProps,
  submissions: (string | MultipleChoiceOption[])[],
  user: string
) => FormEventHandler) => {
  const notify = useNotification();
  return (
      form: FormProps,
      submissions: (string | MultipleChoiceOption[])[],
      user: string
    ): FormEventHandler =>
    (e) => {

    };
};

The types of the outer function's return type arguments are identical to the inner function's arguments.

How can I dry this up so as to avoid the repetition?

CodePudding user response:

In this case just delete the type definitions of the function innards

const useSubmitForm = (): ((
  form: FormProps,
  submissions: (string | MultipleChoiceOption[])[],
  user: string
) => FormEventHandler) => {
  const notify = useNotification();
  return (
    form,
    submissions,
    user
  ): FormEventHandler =>
    (e) => {

    };
};

TypeScript automatically gets those types. Playground link

  • Related