VueBloghyhero6

TS 枚举

2024-08-25 / 2024-08-25 / 36次浏览
enum 枚举 用于定义有名字的常量值

场景是当你需要表示一组固定的值(状态、选项、类型)时,使用enum

例:
enum Status {
    Pending, // 0
    InProgress, // 1
    Completed, // 2
}

const currentStatus: Status = Status.Pending;
console.log(currentStatus); // 输出 0

对比 interface
用于定义接口对象,以及接口对象的属性

也可以定义常量
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
let color: Colors = Colors.Red;
console.log(color)
常量的使用方法

type 类型别名
联合类型,比如该类型的值只能是上面几个值其中之一
type Colors = "RED" | "GREEN" | "BLUE"
const color: Colors = "RED"; // 正确,"RED" 是 Colors 类型的一个成员 console.log(color); // 输出 "RED"