在TypeScript中将值与枚举进行比较并不明显 [英] Comparing value to enum isn't obvious in TypeScript

查看:119
本文介绍了在TypeScript中将值与枚举进行比较并不明显的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有非常简单的代码:

enum Color { BLUE, RED }

class Brush { 
    color: Color

    constructor(values) { 
        this.color = values.color
    }
}

let JSON_RESPONSE = `{"color": "BLUE"}`

let brush = new Brush(JSON.parse(JSON_RESPONSE))

现在我要检查:

console.log(brush.color === Color.BLUE)

它返回 false

我尝试了

brush.color === Color[Color.BLUE]

但是,当然,

问题是如何进行基本比较 enum ===枚举

推荐答案

问题是TypeScript 枚举是实际上是命名为数字常数。

The problem is that TypeScript enums are actually "named numeric constants."

来自有关枚举 s


枚举允许我们定义一组名为

Enums allow us to define a set of named numeric constants.

枚举的主体由零个或多个枚举成员组成。枚举成员具有与其关联的数值( sic )。 。 。

The body of an enum consists of zero or more enum members. Enum members have numeric value (sic) associated with them . . .

您应该使用字符串文字类型代替:

type Color = "BLUE" | "RED";


type Color = "BLUE" | "RED";

class Brush { 
    color: Color

    constructor(values) { 
        this.color = values.color
    }
}

let JSON_RESPONSE = `{"color": "BLUE"}`

let brush = new Brush(JSON.parse(JSON_RESPONSE))

console.log(brush.color === "BLUE"); //=> true

这篇关于在TypeScript中将值与枚举进行比较并不明显的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆