Issue
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?
Solution
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)
Answered By - Phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.