如何判断一个数是否在枚举中?

作者站长头像
站长
· 阅读数 14

enum popupCount {
    default = '0',
    single    = '1',
    double    = '2',
    many    = '4',
    error    = '404',
}

function AA(count:popupCount) {
    return `http//localhost:5000/api/abc/#${count}`
}

通常来说 AA(popupCount.default) 这样调用。但有的时候是传参过来,可能拿到其他数字。希望能改成

function AA(count:popupCount) {
    if(count is popupCount) // 这里的判断不知道该怎么写
        return `http//localhost:5000/api/abc/#${count}`
    else
        return ''
}

以下写法也没用

Object.values(popupCount).includes(count)
count in popupCount
回复
1个回答
avatar
test
2024-07-16
const test = (value:any): value is popupCount => Object.values(popupCount).includes(value)
const result1 = test("0")
const result2 = test("1")
const result3= test("500")
console.log(result1, result2, result3)

https://stackoverflow.com/que...

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容