[SOLVED] How to type less verbosely


I was wondering if it’s possible to type handleSubmit in a less verbose way. Maybe creating a new interface by putting the eventDefault. How would I do that?

  import {Project} from "../ProjectsPage/Project";

interface FormTypeProps {
    onCancel: () => void;
    onSave: (project: Project) => void;

export function ProjectForm({onCancel, onSave}: FormTypeProps) {
    const handleSubmit = (event: { preventDefault: () => void; }) => {
        onSave(new Project({name: 'Update Project'}))

    return (
        <form className="input-group vertical" onSubmit={handleSubmit}>
            <label htmlFor="name">Project Name</label>
            <input type="text" name="name" placeholder="enter name"/>
            <label htmlFor="description">Project Description</label>
            <textarea name="description" placeholder="enter description"/>
            <label htmlFor="budget">Project Budget</label>
            <input type="number" name="budget" placeholder="enter budget"/>
            <label htmlFor="isActive">Active?</label>
            <input type="checkbox" name="isActive"/>
            <div className="input-group">
                <button className="primary bordered medium">Save</button>
                <button type="button" className="bordered medium" onClick={onCancel}>


You can use React.FormEvent as the type of the event parameter:

import React, { FormEvent } from "react";

// ...

const handleSubmit = (event: FormEvent) => {
    // ...

React has its own synthetic event types for the various events, which you use when setting up the handler the way you are, with an onXyz property on the element. (When setting up a handler via addEventListener, which is still sometimes necessary, it’s important not to use React’s synthetic event types, since you’re not setting up a React event handler, you’re setting up a DOM event handler. But with the way you’re doing it, you want the synthetic type.)

You could type the function itself as a FormEventHandler<HTMLFormElement>:

import React, { FormEvent } from "react";

// ...

const handleSubmit: FormEventHandler = (event) => {
    // ...

Note that both FormEvent and FormEventHandler are generic types, accepting a type argument for the type of element that target will be. The default is Element, which is often sufficient, but you could also supply HTMLFormElement (e.g., FormEvent<HTMLFormElement>) if you wanted to be more thorough.

Answered By – T.J. Crowder

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *