Enum 枚举类型

2022-04-12  本文已影响0人  泡杯感冒灵

JS写法

const Status = {
  OFFLINE: 0,
  ONLINE: 1,
  DELETED:2
}

function getResult(status:number) {
  if (status === Status.OFFLINE) {
    return 'offline';
  } else if (status === Status.ONLINE) {
    return 'online';
  } else if (status === Status.DELETED) {
    return 'deleted';
  }
  return 'error';
}

const result = getResult(Status.OFFLINE);
console.log(result);
枚举类型
enum Status {
  OFFLINE,
  ONLINE,
  DELETED
}

console.log(Status.OFFLINE);  // 0
console.log(Status.ONLINE);   // 1
console.log(Status.DELETED);  // 2

function getResult(status:any) {
  if (status === Status.OFFLINE) {
    return 'offline';
  } else if (status === Status.ONLINE) {
    return 'online';
  } else if (status === Status.DELETED) {
    return 'deleted';
  }
  return 'error';
}

// const result = getResult(0); 
// console.log(result); // offline

const result = getResult(Status.OFFLINE);
console.log(result); // offline
enum Status {
  OFFLINE = 1,
  ONLINE,
  DELETED
}
// 0 
// 5
// 6
enum Status {
  OFFLINE,
  ONLINE = 5,
  DELETED
}


enum Status {
  OFFLINE = 1,
  ONLINE ,
  DELETED
}
console.log(Status [0])  // undefined

枚举类型的反向映射

enum Status {
  OFFLINE,
  ONLINE ,
  DELETED
}

console.log(Status[0]);  // OFFLINE

emum枚举类型,应用场景,就是status状态码这种固定的几个值的情况

上一篇下一篇

猜你喜欢

热点阅读