typescript - 在字符串值成员中使用枚举

假设这些是我的枚举:

enum Direction {
    Up = `1`,
    Down = '2',
    Left = '3',
    Right = '4',
}

enum Direction2 {
    Up = Direction.Up
}

只要第二个枚举的值来自另一个枚举,上述情况就有效。但为什么这是无效的?

enum Direction2 {
    Up = Direction.Up,
    Down = '2'
}

我查看了 typescript enum doc但找不到任何理由。据我所见,Direction2 中的两个值都是一个字符串,应该允许。我知道如果我将 Direction2 更改为 json 可以解决此问题:

let Direction2 = {
    Up: Direction.Up,
    Down: '2'
}

但我更愿意将其保留为枚举。

最佳答案

你的语法应该抛出错误:

Computed values are not permitted in an enum with string valued members.

来自 Typescript 首席开发人员,这是故意不允许的。:

String enums are syntactically differentiated from numeric enums by having string literals in all initialization positions. It's also the case that we need to produce a union type (instead of a branded primitive type) for a string literal enum, which aren't really sourced from consts without explicit type annotations.

https://github.com/Microsoft/TypeScript/issues/20440

所以您遇到的问题不是在其他枚举中引用枚举声明。只是它们的其他枚举值是字符串值。请参阅以下内容:

// valid
enum Test{
    A = 1,
    B = 2
}
enum AnotherTest{
    A = Test.B,
    B = 2
}
/////////////////////////////
// valid
enum Test{
    A = "1",
    B = "2"
}
enum AnotherTest{
    A = Test.B,
    B = 2
}
/////////////////////////////
// INVALID
enum Test{
    A = "1",
    B = "2"
}
enum AnotherTest{
    A = Test.B,
    B = "2"
}

https://stackoverflow.com/questions/61655368/

相关文章:

c# - w[警告]未找到测试结果文件 azure devops

spring-boot - 如何将Keycloak注册到Spring Eureka Server

python - 你如何使用 python-rtmidi 获取 midi 事件

ios - 在 iOS 13 中获取 Root View Controller 的正确方法是什么?

python - 包含 json 格式列的 Dask 数据框

html - 如何在没有 JavaScript 的情况下设置 CSS 动画速度?

java - Netbeans 中的 JUnit 5 测试

google-app-engine - 如何使用 Google Cloud Tasks 扩展拉取队列

kubernetes - 无法从普罗米修斯适配器检索自定义指标

python - 逐步将新数据附加并绘制到 matplotlib 行