[Typescript] Typescript Enums vs Booleans when Handling State

Handling state with Typescript enums, instead of booleans, is preferred because:
- Enums are more readable
- Enums can have as many states as you need while booleans only have 2
- You only need to keep track of state with 1 variable when using enums

 

TypeScript enums are number based. This means that numbers can be assigned to an instance of the enum, and so can anything else that is compatible with number.

enum Color {
    Red,
    Green,
    Blue
}
var col = Color.Red;
col = 0; // Effectively same as Color.Red

 

enum CardSuit {
    Clubs,
    Diamonds,
    Hearts,
    Spades
}

// Sample usage
var card = CardSuit.Clubs;

// Safety
card = "not a member of card suit"; // Error : string is not assignable to type `CardSuit`

 

你可能感兴趣的:([Typescript] Typescript Enums vs Booleans when Handling State)