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
- 默认情况下,枚举类型 从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
emum枚举类型,应用场景,就是status状态码这种固定的几个值的情况
网友评论