【问题标题】:Type 'symbol' is not assignable to type类型“符号”不可分配给类型
【发布时间】:2018-05-12 18:24:47
【问题描述】:

阅读reference

而不是使用常量变量声明,

const directionUp: symbol = Symbol();
const directionDown: symbol = Symbol();
const directionLeft: symbol = Symbol();
const directionRight: symbol = Symbol();

在下面的代码中使用枚举类型,

enum Direction {
    Up = Symbol(),
    Down = Symbol(),
    Left = Symbol(),
    Right = Symbol(),
}

如何解决以下错误?

$ tsc --version
Version 2.8.3
$ tsc
tstut.ts(2,10): error TS2322: Type 'symbol' is not assignable to type 'Direction'.
tstut.ts(3,12): error TS2322: Type 'symbol' is not assignable to type 'Direction'.
tstut.ts(4,12): error TS2322: Type 'symbol' is not assignable to type 'Direction'.
tstut.ts(5,13): error TS2322: Type 'symbol' is not assignable to type 'Direction'.

【问题讨论】:

  • enum 中是否允许使用符号?
  • 这是无效的。只需使用consts

标签: typescript ecmascript-6


【解决方案1】:

Symbol 不能用于枚举,只能用于字符串和数字。

这不是必需的,因为Symbol 的使用是唯一标识符,但枚举中的属性已经符合该请求:

enum E1 {
   First = 1
}

enum E2 {
   First = 1
}

const p: E2 = E1.First; // error, even if the two values are theoretically compatible.

【讨论】:

  • 这看起来很有必要,因为它不需要让您思考是否分配1"UP""RED"。值最好是匿名的,但需要分配值。有时,很难选择价值观。在enum 类型中,常量名称很重要,但值不重要。
  • 不,这不是必需的。您可以将枚举定义为enum E1 { First }
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 2019-06-02
  • 2021-02-22
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多