TypeScript/TS基础知识四-枚举类型

113 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第10天,点击查看活动详情

枚举类型

数字枚举

  1. 数字枚举的取值可以是字面量,也可以是常量,也可以是计算的结果

  2. 如果采取字面量的第一个成员进行赋值,下面的成员的值自动递增

enum Gender{
    Male,
    Female,
}
console.log(Gender.Male) // 0
console.log(Gender.Female) //1
console.log(Gender[0]) // Male
  1. 如果采用常量或计算结果进行赋值,则下面的成员也必须初始化 错误的例子
let val = 20;
let num = () => 200
enum Gender {
    Male=val,
    Female
}

image.png 正确的例子

let val = 20;
let num = () => 200
enum Gender {
    Male=val,
    Female=num()
}
console.log(Gender.Male) // 20
console.log(Gender.Female) //200
console.log(Gender[20]) // Male

字符串枚举

  1. 如果采用字面量第一个成员进行赋值,下面的成员也必须赋值
  2. 采用(index)的形式不能获取到内容,需要传入[key]


enum Direction {
    up = 'UP',
    down = 'DOWN'
}
console.log(Direction.up)
console.log(Direction.down)
console.log(Direction['up'])
console.log(Direction['down'])
console.log(Direction[0])  // 错误
console.log(Direction['DOWN'])  //错误

  1. 字符传枚举不能使用常量或者计算结果给枚举值赋值 下面两个都不可以

const value = 'shizebang'
const n = () => "实则棒"
enum User {
    a = value;
    b = n;
}

image.png image.png 4. 它可以使用内部其枚举值来赋值 这个是没问题的,把a赋值给b


const value = 'shizebang'
const n = () => "实则棒"
enum User {
    a = "HTML",
    b = a,
}

异构枚举

枚举中既包含数字也包含字符串,我们称之为异构枚举,如果是字符串枚举,没办法通过原始值取到枚举值 数字枚举什么时候都可以反向拿货,而字符串枚举不可以,



enum Gender {
    Mate = 1,
    FeMate = '女'
}

console.log(Gender.Mate);  // 1
console.log(Gender.FeMate); // 女
console.log(Gender[0]); // undefined
console.log(Gender[1]); // Mate

枚举当类型来用就是一个联合类型而已

enum Gender {
    Mate = 1,
    FeMate = '女'
}

interface IUser {
    a: Gender
}

class Person implements IUser {
    constructor(public a: Gender) {
        this.a = a;
    }
}