Typescript

TS 中 interface,type,enum 的区别

2021-03-09  本文已影响0人  弱冠而不立

interface 接口

在 TypeScript 中,我们使用接口(Interfaces)来定义对象的类型。

在面向对象语言中,接口(Interfaces)是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类(classes)去实现(implement)。

例如:

interface Person {
  name: string;
  say(): string
}

// 使用接口去规范对象的初始化
let worker: Person = {
  name: "打工人";
  say() {
    return "Hello World";
  }
}

// 或者使用类去实现接口
class Boss implements Person {
  constructor(name: string) {
    this.name = name
  }
  say() {
    return "996 is a blessing";
  }
}

type

类型别名用来给一个类型起个新名字。
或者 字符串字面量类型用来约束取值只能是某几个字符串中的一个。

所以 类型别名常用于联合类型。
举例:

type order = string | number
type weekend = "Saturday" | "Sunday"
type workdays = string

type week = weekend | workdays

let foo: order = "123" // √
let foo: order = 123 // √

let nowDay: week = 1 // ×
let nowDay: week = "Sunday" // √
let nowDay: week = "1" // √

enum 枚举类型

枚举(Enum)类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。

枚举成员会被赋值为从 0 开始递增的数字,同时也会对枚举值到枚举名进行反向映射:

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

console.log(Days["Sun"] === 0); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true

console.log(Days[0] === "Sun"); // true
console.log(Days[1] === "Mon"); // true
console.log(Days[2] === "Tue"); // true
console.log(Days[6] === "Sat"); // true

也可以手动赋值:

enum FetchMethods {
  POST = "post",
  GET = "get",
  PUT = "put",
  DELETE = "delete"
}

FetchMethods.POST === "post" //true
上一篇 下一篇

猜你喜欢

热点阅读