TypeScript 2.4+
文字列値を列挙型メンバーに直接割り当てることができるようになりました。
enum Season {
Winter = "winter",
Spring = "spring",
Summer = "summer",
Fall = "fall"
}
詳細については、 #15486を参照してください。
TypeScript 1.8+
TypeScript 1.8以降では、文字列リテラル型を作成して、値の一覧に同じ名前の型とオブジェクトを定義できます。これは、文字列列挙型の予想される動作を模倣しています。
次に例を示します。
type MyStringEnum = "member1" | "member2";
const MyStringEnum = {
Member1: "member1" as MyStringEnum,
Member2: "member2" as MyStringEnum
};
これは文字列列挙型のように機能します:
// implicit typing example
let myVariable = MyStringEnum.Member1; // ok
myVariable = "member2"; // ok
myVariable = "some other value"; // error, desired
// explict typing example
let myExplicitlyTypedVariable: MyStringEnum;
myExplicitlyTypedVariable = MyStringEnum.Member1; // ok
myExplicitlyTypedVariable = "member2"; // ok
myExplicitlyTypedVariable = "some other value"; // error, desired
オブジェクトにすべての文字列を入力してください。そうしないと、上記の最初の例では、変数は暗黙的にに入力されませんMyStringEnum
。