You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
enumDirection{Up,Down,Left,Right,}functionmove(direction: Direction){console.log(direction);}move(30);// ok
这种执行不会报错
字符串枚举不能直接使用字符串赋值
enumStatus{Admin="Admin",User="User",Moderator="Moderator",}declarefunctioncloseThread(threadId: number,status: Status): void;closeThread(10,"Admin");// ^ 💥 This is not allowed!closeThread(10,Status.Admin);// ^ You have to be explicit!
使用联合类型更好
简单形式
typeStatus="Admin"|"User"|"Moderator"declarefunctioncloseThread(threadId: number,status: Status): void;closeThread(10,"Admin");// All good 😄
类枚举风格
constDirection={Up: 0,Down: 1,Left: 2,Right: 3,}asconst;// Get to the const values of any objecttypeValues<T>=T[keyofT];// Values<typeof Direction> yields 0 | 1 | 2 | 3declarefunctionmove(direction: Values<typeofDirection>): void;move(30);// ^ 💥 This breaks!move(0);// ^ 👍 This works!move(Direction.Left);// ^ 👍 This also works!// And now for the Status enumconstStatus={Admin: "Admin",User: "User",Moderator: "Moderator"}asconst;// Values<typeof Status> yields "Admin" | "User" | "Moderator"declarefunctioncloseThread(threadId: number,status: Values<typeofStatus>): void;closeThread(10,"Admin");// All good!closeThread(10,Status.User);// enum style
这些方法不会导致出现枚举存在的问题
The text was updated successfully, but these errors were encountered:
推荐使用联合类型代替枚举类型
枚举的问题
这种执行不会报错
使用联合类型更好
这些方法不会导致出现枚举存在的问题
The text was updated successfully, but these errors were encountered: