Home > Software engineering >  How to accept multiple interfaces when passing React State Setter
How to accept multiple interfaces when passing React State Setter

Time:03-08

Lets say I have two interfaces which share two fields.

interface user {
    id: string;
    email: string;
    name: string
}

interface contactRequest {
    id: string;
    email: string;
    time: Date
}

Is there a way to create a function which will set the state for both of these interfaces?

const setId_Email = (id: string, email: string, setState: Dispatch<SetStateAction<????>>) => {

  setState(prevState => ({
    ...prevState, id, email
   }));
}

What could I put inside the SetStateAction brackets to accept any interface that has an id and email field?

CodePudding user response:

I'd start by defining a common interface, for example

interface Contact {
  id: string;
  email: string;
}

interface User extends Contact {
  name: string;
}

interface ContactRequest extends Contact {
  time: Date;
}

Now you can use the common Contact interface when you're only interested in the shared properties

const setId_Email = <T extends Contact>(
  id: string,
  email: string,
  setState: Dispatch<SetStateAction<T>>
) => {
  setState((prevState) => ({
    ...prevState,
    id,
    email
  }));
};

This can be called with any state setter that extends Contact

const [ user, setUser ] = useState<User>({ ... })
const [ request, setRequest] = useState<ContactRequest>({ ... })

setId_Email(id, email, setUser)
setId_Email(id, email, setRequest)
  • Related