TypeScript(10枚举& 类型别名)

344 阅读1分钟

使用枚举 通过enum关键字定义枚举

数字枚举

如:红绿蓝 Red = 0 Green = 1 Blue = 2 分别代表不同颜色

enum Color {
  red,
  green,
  blue
}
console.log(Color.red, Color[0])

增长枚举

从定义了数字之后开始递增

enum Color {
  red,
  green = 4,
  blue
}
console.log(Color.red, Color.blue)  //0 5

字符串枚举

在一个字符串枚举里,每个成员都必须使用字符串字面量,或另一个字符串枚举成员进行初始化。

enum Color1 {
  red = 'red',
  green = 'green',
  blue = 'blue',
}

异构枚举

枚举可以混合字符串和数字成员

enum Types {
  yes = 1,
  no = 'No'
}

接口枚举

定义一个枚举Types 定义一个接口A 规则如👇

interface Ac {
  red: Types.yes
}
let objs1: Ac = {
  red: Types.yes
}

const 枚举

常量枚举, 不能使用let var定义

const enum Types {
  yes,
  no
} 
let code: number = 0
if (code === Types.yes) {
  console.log('***')
}

反向映射

字符串是无法反向映射的

enum Enum {
  fall
}
let a = Enum.fall
console.log(a)  //0
console.log(Enum[a]) //fall

类型别名

type s = string | number
let strs: s = '3'
strs = 1

//函数的类型别名
type cb = () => string
const fnc1: cb = () => 'Durant' 

//值类型的类型别名
type T = 'off' | 'on'
const str: T = 'off'  //只能是 'off' 或 'on'