Search code examples
typescriptarrow-functions

Definition of data types in Typescript arrow functions


I stumbled across piece of the following code

  const onSubmit: SubmitHandler<IFormInput> = data => console.log(data);

I rewrote it in the form I understand

  const onSubmitFunction = ( data: IFormInput ):void => console.log(data);

But still I wonder what did mean the :SubmitHandler<IFormInput> after the first colon. Submit handler is defined as a type

export type SubmitHandler<TFieldValues extends FieldValues> = (data: TFieldValues, event?: React.BaseSyntheticEvent) => any | Promise<any>;

Thank you.


Solution

  • I rewrote it in the form I understand... But still I wonder what did mean the :SubmitHandler<IFormInput> after the first colon

    That is what it mean! It means exactly what you rewrote.

    The expression const x: Y = means “x is a constant of type Y”.

    The expression const onSubmit: SubmitHandler<IFormInput> = means “onSubmit is a constant of type SubmitHandler, which is to say, the generic type SubmitHandler instantiated with the type IFormInput, which in turn means a function that takes a value of type IFormInput and returns nothing.”

    If you had simply written const onSubmit = data => console.log(data); then the compiler could have inferred that it was function (because of the =>) and that it returned the same type as console.log (nothing), but it would have no way to know what “data” meant.

    Edit: I was asked to clarify what I mean by “the type of a function”.

    A value (or a constant, expression, or variable) can be of function-type, meaning:

    1. it is in fact a function, and not a string or array or whatever
    2. it takes a tuple or list of arguments, of some particular types
    3. it returns a value of some particular type

    The OP’s example, SubmitHandler is probably written something like this:

     type SubmitHandler<T> = (t: T) => void
    

    meaning “a value of type SubmitHandler of T is a function that takes one argument, of type T, and returns no value”.