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