使用枚举我们可以定义一些带名字的常量。 使用枚举可以清晰地表达意图或创建一组有区别的用例。 TypeScript支持数字的和基于字符串的枚举。

    1. const Status = {
    2. OFFLINE: 0,
    3. ONLINE: 1,
    4. DELETED: 2,
    5. };
    6. function getResult(status: number) {
    7. if (status === Status.OFFLINE) {
    8. return "offline";
    9. } else if (status === Status.ONLINE) {
    10. return "online";
    11. } else if (status === Status.DELETED) {
    12. return "deleted";
    13. }
    14. return "error";
    15. }
    16. const result = getResult(Status.OFFLINE);
    17. console.log(result);

    使用枚举类型:

    1. enum Status {
    2. OFFLINE,
    3. online,
    4. DELETED,
    5. }
    6. function getResult(status: number) {
    7. if (status === Status.OFFLINE) {
    8. return "offline";
    9. } else if (status === Status.ONLINE) {
    10. return "online";
    11. } else if (status === Status.DELETED) {
    12. return "deleted";
    13. }
    14. return "error";
    15. }
    16. const result = getResult(Status.OFFLINE);
    17. console.log(result);

    枚举的下标默认是从 0 开始,递增加1,也可以设置默认下标,后面的属性下标会在默认下标基础上递增加1。通过下标,可以查寻到对应的枚举名称