说明
抽象类是定义规范的,并且里面也可以实现业务规范。而接口的作用主要是实现规范,一旦一个对象或者一个类使用了某个接口,那么接口中的要求就必须在对象或者类中实现。
使用
下面通过代码演示了在类中使用接口进行约束:
// 定义一个接口interface animation {name: string,move: ()=>void,}// 创建一个抽象类abstract class Animation {// 设置 普通的属性public num: number = 100;// 定义一个普通的方法public fn(): void {console.log(123);}}// 创建一个玩家类继承自抽象类class Player extends Animation implements animation {// 子类继承了抽象类就要实现抽象类中的属性和方法public name: string = '玩家';public move(): void {console.log(`${this.name}移动`);}}const p1 = new Player();p1.move();// 使用抽象类中定义的普通的属性和方法console.log(p1.num);p1.fn();
想要通过接口约束类,需要使用implements来设置。
在定义类的时候,还可以通过接口来约束属性。
interface UserInterface {
name: string;
age: number;
}
class User {
private _userInfo: UserInterface;
constructor(info: UserInterface) {
this._userInfo = info;
}
public get userInfo(): UserInterface {
return this._userInfo;
}
}
注意
总结
一个类可以同时接收抽象类和接口的双重约束。
