轉發node
項目實踐倉庫git
https://github.com/durban89/typescript_demo.git tag: 1.3.7
爲了保證後面的學習演示須要安裝下ts-node,這樣後面的每一個操做都能直接運行看到輸出的結果。github
npm install -D ts-node
後面本身在練習的時候能夠這樣使用typescript
npx ts-node 腳本路徑
使用枚舉咱們能夠定義一些帶名字的常量。 使用枚舉能夠清晰地表達意圖或建立一組有區別的用例。 TypeScript支持數字的和基於字符串的枚舉。npm
存在一種特殊的非計算的常量枚舉成員的子集:字面量枚舉成員。 字面量枚舉成員是指不帶有初始值的常量枚舉成員,或者是值被初始化爲ide
當全部枚舉成員都擁有字面量枚舉值時,它就帶有了一種特殊的語義。學習
首先,枚舉成員成爲了類型! 例如,咱們能夠說某些成員 只能是枚舉成員的值:spa
enum ShapeKind { Circle, Square, } interface Circle { kind: ShapeKind.Circle, radius: number, } interface Square { kind: ShapeKind.Square, sideLength: number, } let c: Circle = { kind: ShapeKind.Square, redius: 100, }
運行後會有以下錯誤提示code
$ npx ts-node src/generics_8.ts ⨯ Unable to compile TypeScript: src/generics_8.ts(17,5): error TS2322: Type 'ShapeKind.Square' is not assignable to type 'ShapeKind.Circle'.
另外一個變化是枚舉類型自己變成了每一個枚舉成員的 聯合。 雖然咱們尚未討論[聯合類型](./Advanced Types.md#union-types),但你只要知道經過聯合枚舉,類型系統可以利用這樣一個事實,它能夠知道枚舉裏的值的集合。 所以,TypeScript可以捕獲在比較值的時候犯的愚蠢的錯誤。 例如:blog
enum E { Foo, Bar, } function f(x: E) { if (x !== E.Foo || x !== E.Bar) { } }
運行後會有以下錯誤提示
$ npx ts-node src/generics_8.ts ⨯ Unable to compile TypeScript: src/generics_8.ts(27,23): error TS2367: This condition will always return 'true' since the types 'E.Foo' and 'E.Bar' have no overlap.
這個例子裏,咱們先檢查 x是否不是 E.Foo。 若是經過了這個檢查,而後 ||會發生短路效果, if語句體裏的內容會被執行。 然而,這個檢查沒有經過,那麼 x則 只能爲 E.Foo,所以沒理由再去檢查它是否爲 E.Bar。
本實例結束實踐項目地址
https://github.com/durban89/typescript_demo.git tag: 1.3.8