2016-09-30 120 views
17

在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文件,但顯然情況並非如此。

回答

7

還有另一種方法:如果你不想生成的JavaScript代碼以任何方式受到影響,您可以使用類型轉換:

let e1: E = E.A 
let e2: E = E.B 


if (e1 as E === e2 as E) { 
    console.log("equal") 
} 

在一般情況下,這是通過控制流爲基礎的類型引起的推理。隨着當前打字稿實現,它關閉時函數調用參與,所以你也可以這樣做:

let id = a => a 

let e1: E = id(E.A) 
let e2: E = id(E.B) 

if (e1 === e2) { 
    console.log('equal'); 
} 

奇怪的是,如果id函數聲明爲返回完全相同的類型,仍然沒有錯誤作爲其agument:

function id<T>(t: T): T { return t; } 
5

嗯,我想我找到東西的作品:

if (e1.valueOf() === e2.valueOf()) { 
    console.log("equal") 
} 

但我有點驚訝,這不是在文檔中提及任何地方。

+1

這並不爲我工作比較。我得到一個未定義的 – dave0688

1

只(以打字稿2.2.1)爲我工作的事情是這樣的:

if (E[e1] === E[e2]) { 
    console.log("equal") 
} 

此來比較T他表示名字的字符串(例如。 「A」和「B」)。

0

如果是能夠在兩個枚舉這個

if (product.ProductType && 
     (product.ProductType.toString() == ProductTypes[ProductTypes.Merchandises])) { 
     // yes this item is of merchandises 
    } 

與ProductTypes是這個export enum ProductTypes{Merchandises,Goods,...}