Is there a way, in javascript (no typescript), to specify that the parameter of a method has to be "one of" [value1, value2]?
For example, if I have a function:
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
}
if there any way to specify that action has to be one of ["add", "delete"] ?
// Something like this...
const handleCommentAction = (action: ["add", "delete"]) => {
or is impossible?
It can be enforced at runtime only by throwing an error or something:
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
} else {
throw new Error('wrong parameter');
}
}
A better solution would be to use JSDoc to indicate that the argument must be of a particular type:
/**
* @param {'add' | 'delete'} action - The action to perform
*/
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
};
But this is only documentation, not a requirement of consumers of handleCommentAction.
A more elaborate solution (definitely worth it in larger projects, but arguably overkill for small scripts) would be to use TypeScript or some other type-aware system:
const handleCommentAction = (action: 'add' | 'delete') => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With