在TypeScript中,我想比較兩個包含枚舉值的變量。這裏是我最小的代碼示例:如何比較TypeScript中的枚舉
enum E {
A,
B
}
let e1: E = E.A
let e2: E = E.B
if (e1 === e2) {
console.log("equal")
}
當tsc
(V 2.0.3),我收到以下錯誤編譯:
TS2365: Operator '===' cannot be applied to types 'E.A' and 'E.B'.
同樣的,==
,!==
和!=
。 我試着添加const
關鍵字,但似乎沒有效果。 的TypeScript spec說以下內容:
4.19.3 The <, >, <=, >=, ==, !=, ===, and !== operators
These operators require one or both of the operand types to be assignable to the other. The result is always of the Boolean primitive type.
這(我認爲)解釋了錯誤。但我怎麼能繞它呢?
旁註
我使用了Atom編輯器atom-typescript,我沒有得到我的編輯器的任何錯誤/警告。但是當我在同一個目錄中運行tsc
時,我得到上面的錯誤。我以爲他們應該使用相同的tsconfig.json
文件,但顯然情況並非如此。
這並不爲我工作比較。我得到一個未定義的 – dave0688