Search code examples
typescriptreact-hook-formmethod-signature

How to read a TypeScript signature with multiple arrows and generics?


I am trying to understand this TypeScript signature from react-hook-forms:

handleSubmit: <TSubmitFieldValues extends FieldValues = TFieldValues>(onValid: SubmitHandler<TSubmitFieldValues>, onInvalid?: SubmitErrorHandler<TFieldValues>) => (e?: React.BaseSyntheticEvent) => Promise<void>;

Especially, but not only I want to understand:

  1. What does the equals sign in the generic type mean?

    <TSubmitFieldValues extends FieldValues = TFieldValues>

  2. How can there be two arrows in the signature?

    [removed for shortening] => (e?: React.BaseSyntheticEvent) => Promise<void>

Would be great if someone could explain the signature step-by-step, thanks!


Solution

  • What does the equals sign in the generic type mean?

    It's the default type.

    How can there be two arrows in the signature?

    It's a function that returns another function. For example, this function:

    const myWeirdAdd = arg1 => arg2 => arg1+arg2;
    

    Can we called this way:

    myWeirdAdd(1)(2); // returns 3;
    

    And it's type would be:

    type CurriedAdd = (arg1: number) => (arg2: number) => number;