skip to Main Content

I want one of my inputs to be able only assign values of certain strings (Vehicle brands in this case). On the Select component below I want the event type to only accept this 4 strings. How can I do that? How should I type myEventType?

......
    const [brand, setBrand] = useState<"All" | "Toyota" | "Ford" | "BMW">("All")

    type myCurrentTarget = Override<react.SyntheticEvent.currentTarget, { value: "All" | "Toyota" | "Ford" | "BMW" }>
    type myEventtype = Override<react.SyntheticEvent, myCurrentTarget>


......

return (
               <Select
                    value={brand}
                    onChange={e:myEventtype => setBrand(e.currentTarget.value)}
                    data={["All", "Toyota", "Ford", "BMW"]}
                />
)

2

Answers


  1. You can define a type to hold values of your vehicle brands like this:
    type Brand = "All" | "Toyota" | "Ford" | "BMW";

    Change your state hook like this:
    const [brand, setBrand] = useState<Brand>("All");

    Then define your custom event like this:

    type myEventtype = React.SyntheticEvent<{
      value: Brand;
    }>;
    
    Login or Signup to reply.
  2. create an interface.

    Please refer below lines

    type valueType= "All" | "Toyota" | "Ford" | "BMW";
    interface myEventtype{
        currentTarget:{
            value: valueType,
            [key:string]:any
        },
        [key:string]:any
    }
    
    return (
               <Select
                    value={brand}
                    onChange={e:myEventtype => setBrand(e.currentTarget.value)}
                    data={["All", "Toyota", "Ford", "BMW"]}
                />
    )
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search