类型“符号”不能分配给类型

时间:2018-05-12 18:24:48

标签: typescript ecmascript-6

阅读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'.

1 个答案:

答案 0 :(得分:2)

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

并且没有必要,因为使用Symbol是唯一的标识符,但enumarion中的属性已经符合该请求:

enum E1 {
   First = 1
}

enum E2 {
   First = 1
}

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