zl程序教程

您现在的位置是:首页 >  工具

当前栏目

[Typescript] Typescript Enums vs Booleans when Handling State

vstypescript when State Handling
2023-09-14 09:00:54 时间

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`