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);
枚举类型
- 写一个枚举类型 Status
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
- 默认情况下,枚举类型 从0开始,如果希望OFFLINE值是1,ONLINE是1,DELETED是3,可以这样写
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