本文以活动状态为例介绍 ts 中的枚举类型
js 定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const statusObj = { unplayed: 0, underway: 1, end: 2 };
function getServe(status) { if (status === statusObj.unplayed) { return "未开始"; } else if (status === statusObj.underway) { return "进行中"; } else if (status === statusObj.end) { return "已结束"; } }
const resultJs = getServe(0); console.log(`当前活动状态为${resultJs}`);
|
枚举中默认值为下标,即 index 值,从 0 开始
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| enum StatusEnum { unplayed = 1, underway, end }
function getServeTs(status: number): string { if (status === StatusEnum.unplayed) { return "未开始"; } else if (status === StatusEnum.underway) { return "进行中"; } else if (status === StatusEnum.end) { return "已结束"; } else { return "未匹配到该活动"; } }
console.log(StatusEnum.unplayed); console.log(StatusEnum.underway); console.log(StatusEnum.end);
const resultTs = getServeTs(0); console.log(`当前活动状态为 ${resultTs}`);
|