检查打字稿枚举是否有TS错误或不工作的值

发布于 2025-01-25 20:37:20 字数 448 浏览 1 评论 0原文

以下代码可以做我想做的事情:

BallStatusTypes.safe === BallStatusTypes[status] ? 'ball' : 'ball-danger'

尽管给了我这个错误:此条件总是会返回“ false”,因为类型的“ ballstatustypes”和“ string”没有重叠。

以下,错误,错误免费代码不做我想做的事情:

status === BallStatusTypes.safe ? 'ball' : 'ball-danger'

枚举是:

export enum BallStatusTypes {
  danger = 1,
  safe = 2
}

如何修复我的代码,以便在没有错误的情况下完成我想要的操作?

The following code does what I want it to do:

BallStatusTypes.safe === BallStatusTypes[status] ? 'ball' : 'ball-danger'

Despite giving me this error: This condition will always return 'false' since the types 'BallStatusTypes' and 'string' have no overlap.

The following, error free code does NOT do what I want it to do:

status === BallStatusTypes.safe ? 'ball' : 'ball-danger'

The enum is:

export enum BallStatusTypes {
  danger = 1,
  safe = 2
}

How can I fix my code so that it does what I want it to do, without errors?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飞烟轻若梦 2025-02-01 20:37:20

我最终解决了这一点:

export enum BallStatusTypes {
  danger = 'danger',
  safe = 'safe'
}

似乎我对枚举创建对象映射到数字或字符串的方式似乎有问题。而且,Typescript不知道(在上述值中执行表达式)是否应该比较数值版本或状态的字符串版本。

I ended up resolving this with:

export enum BallStatusTypes {
  danger = 'danger',
  safe = 'safe'
}

It seems I was having issues with the way enums create objects mapping to either a number or a string. And, typescript was unaware (when performing expressions on said value) of weather or not it should be comparing the numerical version or the string version of the status.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文