延續前一篇,今天重點放在 enum 跟 type。

enum TestEnum {
    One = 1,
    Two = 2,
    Three = 3
};

enum TestEnum2 {
    One = "one",
    Two = "two",
    Three = "three"
};

let enumVal: TestEnum = TestEnum.Three;
if (enumVal == TestEnum.Three) {
    console.log(enumVal);
}

let enumValue1: number = TestEnum.One;
let enumValue2: string = TestEnum2.Two;
};

如果很熟悉 C# 了,對於 enum 應該很快就能理解,只是有一點不同,在 C# 中 enum 的值只能是整數,在 TypeScript 中想指定為字串也沒問題。

再來是 type,筆者認為它最適用的場合在於處理 JSON 資料,請看下列程式碼:

type jsonType = {
    name: string
    age: number
    readonly sex: boolean
};

type jsonType2 = {
    school: string
    city: string
};

let info: jsonType = {
    name: "Peter",
    age: 18,
    sex: true
};

jsonStr = JSON.stringify(info);
let info2: jsonType = JSON.parse(jsonStr);

在 C# 中通常都是定義一個 class 來處理 JSON 資料,但在 TypeScript 中有 type 這樣的形式可以更簡單地處理 JSON 資料,畢竟只有處理資料,也不需要 class 中的 method。

參考資料