简体   繁体   English

javascript - 两个可能值之一的参数

[英]javascript - parameter one of two possible values

Is there a way, in javascript (no typescript), to specify that the parameter of a method has to be "one of" [value1, value2]?有没有办法,在 javascript(无打字稿)中,指定方法的参数必须是“一个”[value1,value2]?

For example, if I have a function:例如,如果我有一个 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"]?是否有任何方法可以指定该操作必须是 ["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:更好的解决方案是使用JSDoc来指示参数必须是特定类型:

/**
 * @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 .但这只是文档,而不是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:一个更复杂的解决方案(在大型项目中绝对值得,但对于小型脚本来说可能是过度杀伤力)是使用TypeScript或其他一些类型感知系统:

const handleCommentAction = (action: 'add' | 'delete') => {
    if (action === "add") {
        setTotalComments(totalComments + 1);
    } else if (action === "delete") {
        setTotalComments(totalComments - 1);
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM