javascript-两个可能值之一的参数
在javascript(无类型脚本)中,是否有办法指定方法的参数必须是[value1,value2]中的“一个” 例如,如果我有一个函数:javascript-两个可能值之一的参数,javascript,Javascript,在javascript(无类型脚本)中,是否有办法指定方法的参数必须是[value1,value2]中的“一个” 例如,如果我有一个函数: const handleCommentAction = (action) => { if (action === "add") { setTotalComments(totalComments + 1); } else if (action === "delete") {
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
}
如果有任何方法指定该操作必须是[“添加”、“删除”]中的一种
或者是不可能的?只有在运行时抛出错误或其他东西,才能强制执行该操作:
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
} else {
throw new Error('wrong parameter');
}
}
更好的解决方案是使用指示参数必须为特定类型:
/**
* @param {'add' | 'delete'} action - The action to perform
*/
const handleCommentAction = (action) => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
};
但这只是文档,不是handlecommentation
消费者的要求
一个更复杂的解决方案(在较大的项目中绝对值得,但对于小脚本来说可能有些过分)是使用或其他一些类型识别系统:
const handleCommentAction = (action: 'add' | 'delete') => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
};
JavaScript没有类似的东西,但是有。TypeScript是一个有效的答案吗?或者这仅仅是为了JavaScript?@Wyck no typescriptNote:asker明确要求不使用typescript,尽管typescript可能对其他人有用。
const handleCommentAction = (action: 'add' | 'delete') => {
if (action === "add") {
setTotalComments(totalComments + 1);
} else if (action === "delete") {
setTotalComments(totalComments - 1);
}
};