0

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.

2
  • SubmitHandler is a generic type. What specifically are you confused about? Commented Dec 31, 2022 at 15:31
  • about "why there are any types defined before the = sign". i am new to the arrow function, so I see there is input datatype, output datatype but what is that SubmitHandler type? Is it input, is it output? Commented Dec 31, 2022 at 22:36

1 Answer 1

1

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”.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah, here I am confused "onSubmit is a constant of type SubmitHandler,".For me function has input and output data type. But how can function has some type? Except of output type and input type.
@Puser — [response in edit]

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.