Search code examples
reactjstypescripttypescript-typingstsx

Reactjs is there any shortcut for multiple element type declaration


I am getting values from the form. I am using tsx for my project. But I am much unhappy to use a long element type like this:

handleChange = (e:React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement> | React.ChangeEvent<HTMLSelectElement>, id: string ) =>{
        e.preventDefault();
        const {value} = e.target;
        this.setState((prev) => ({fields: {...this.state.fields, [id]:value}}));
        console.log(id, this.state.fields);
    }

where the e ( event ) has:

e:React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement> | React.ChangeEvent<HTMLSelectElement>

such a long type declaration. is there any way to shorten this? or any other type help to take care of all form elements?

Thanks in advance.


Solution

  • Well, you could do this:

    handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>, id: string ) =>{
    

    Which is definitely a bit more concise. Or as was mentioned, you could simply alias your type declaration with type:

    type FormChangeEvent = React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>;
    
    // ...
    
    handleChange = (e: FormChangeEvent, id: string ) =>{
    

    But aside from that, as far as I'm aware there is no existing type alias that encompasses the exact change events you're looking for. Nor, really, should there be, because those elements have different type definitions for a reason, and e.target should reflect them accordingly.

    Depending on your use case, you could just define a simple, limited type for the event that gives you only the type info you actually need. Doing such a thing is fairly common in my experience, for the exact reason you have run into - sometimes concision and simplicity is more valuable than kitchen sink type completionism.

    handleChange = (e: { target: { value: string}; preventDefault: () => {} }, id: string ) =>{
    

    Edit: another thing you can do here is simply type e as any. If you know what you're doing and are careful, this is fairly safe - or, at least, no more dangerous than the days before we had TypeScript.

    handleChange = (e: any, id: string ) =>{