Reputation: 143
I have a reusable component that I frequently use throughout my app for displaying several checkboxes as a group.
My problem comes when passing the functions designed to handle the check actions as they're usually specifically typed to the checkboxes I'm displaying.
type Status = "Enabled" | "Disabled";
function updateStatus(status: Status) {
// Some side effects
}
But in my reusable component I'm trying to keep it as generic as possible with the required props type:
type CheckboxProps = {
toggleCheckbox: (title: string) => void;
// Other props
}
Obviously this fails. I've tried making the props generic and extending them, but the two functions don't extend each other either.
At the moment I'm handling this using as when passing them, but I'd rather avoid doing this at all.
Is it possible to make a generic prop function to any type of string literal union in this way?
Upvotes: 2
Views: 303
Reputation: 2878
You are able to make your type as generic. so when you will initialize it you can say it will be type of Status. The point is generic has to be defined before initializing your function.
type Status = 'Enabled' | 'Disabled';
function updateStatus(status: Status) {
// Some side effects
}
type CheckboxProps <T extends string> = {
toggleCheckbox: (title: T) => void;
// Other props
};
const prop: CheckboxProps<Status> = {
toggleCheckbox: updateStatus,
};
prop.toggleCheckbox('Disabled');
Upvotes: 1