Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - parameter one of two possible values

Tags:

javascript

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?

like image 961
Victor Molina Avatar asked Apr 09 '26 00:04

Victor Molina


1 Answers

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);
    }
};
like image 95
CertainPerformance Avatar answered Apr 10 '26 23:04

CertainPerformance