typescript进阶(二):interface 和 class 的区别

11,308 阅读2分钟

Typescript 中 interface 和 class 的区别?

interface: 接口只负责声明成员变量类型,不做具体实现。

class:类既声明成员变量类型并实现。

interface是什么?

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

TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。

例如:

interface Person {
 name: string;
 age: number;
}

上述例子就是一个最简单的接口,分别有两个属性分别叫做name和age,对应的值是一个字符串和一个数字。利用接口约束了传入变量的内容,当你不遵守这个约定时,typescript就会抛出一个错误。

Class是什么?

传统方法中,JavaScript 通过构造函数实现类的概念,通过原型链实现继承。而在 ES6 中,我们终于迎来了 class。TypeScript 除了实现了所有 ES6 中的类的功能以外,还添加了一些新的用法。(今天只讲述类与interface却别,具体类的其他特性可参考官方

//类Person
class Person {
 name: string;
 age: number;
 constructor(name: string, age: number) {
  this.name = name;
	this.age = age;
 }
};

//类充当接口使用,接口中只包含其中的实例属性和实例方法(constructor和static不在其中)
const person: Person = {
 name: '张三',
 age: 18
};

//接口继承类
interface Person1 extends Person{
 sex: string,
 printName() : void
};

const person1: Person1 = {
 name: '张三',
 age: 18,
 sex: '男',
 printName() {
    console.log(this.name) 
 }
};

//类实现接口
class Person2 implements Person1 {
  name: string;
  age: number;
  sex: string;
  email: string;
  printName() {
    console.log(this.name)
  };
}

总结

Typescript中声明class,实际上,除了会创建一个类之外,同时也会创建一个同名的interface(同名的interface只包含其中的实例属性和实例方法)。所以class既可以当作类来使用,也可以当作interface来使用。

个人博客地址,有兴趣的可以看一看