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


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
阅读 5.5k
3 个回答
✓ 已被采纳
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...

function AA(count: popupCount) {
  if (typeof  count=== 'number' && count in popupCount) {
    return `http//localhost:5000/api/abc/#${count}`;
  } else {
    return '';
  }
}

首先你应该明白 enumtype ,interface不同 在 TypeScript 编译后,enum 被转换为 JavaScript 对象

enum popupCount {
    default = '0', // 注意需要将数字改成string 否则是双向的
    single    = '1',
    double    = '2',
    many    = '4',
    error    = '8',
} // => `{default: 0, single: 1, double: 2, many: 4, error: 8}`

function AA(count:popupCount) {
    if(count in popupCount)
        return `http//localhost:5000/api/abc/#${count}`
    else
        return ''
}
AA(popupCount.default)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题