TypeScript 2.4
ตอนนี้มี enums สตริงเพื่อให้รหัสของคุณทำงาน:
enum E {
hello = "hello",
world = "world"
};
🌹
TypeScript 1.8
ตั้งแต่ TypeScript 1.8 คุณสามารถใช้ชนิดตัวอักษรของสตริงเพื่อมอบประสบการณ์ที่เชื่อถือได้และปลอดภัยสำหรับค่าสตริงที่มีชื่อ (ซึ่งบางส่วนใช้ enums)
type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay
foo = "asdf"; // Error!
เพิ่มเติมได้ที่https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
การสนับสนุนแบบดั้งเดิม
Enums ใน TypeScript ขึ้นอยู่กับจำนวน
คุณสามารถใช้คลาสกับสมาชิกแบบสแตติกได้แม้ว่า:
class E
{
static hello = "hello";
static world = "world";
}
คุณสามารถไปได้ด้วย:
var E = {
hello: "hello",
world: "world"
}
อัปเดต:
ขึ้นอยู่กับข้อกำหนดเพื่อให้สามารถทำสิ่งvar test:E = E.hello;
ต่อไปนี้ได้ตรงตามนี้:
class E
{
// boilerplate
constructor(public value:string){
}
toString(){
return this.value;
}
// values
static hello = new E("hello");
static world = new E("world");
}
// Sample usage:
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;
console.log("First value is: "+ first);
console.log(first===third);