好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

typescript中的类与接口的关系

类实现接口

接口可以规定一个类的定义必须包含某些内容。类实现接口使用关键字 implements。

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

  //   类实现接口 
 class User implements UserInterface{
  name:string;
  age:number;
  constructor(name:string,age:number){
      this .name =  name
      this .age =  age
  }
} 

 

需要注意的是,使用接口定义的类,接口检测的是该类创建的实例是否符合接口规范,如果改一下上面的例子就会报错了:

 class User implements UserInterface{
  static name:string;   //   error,加上 static,该属性不会添加到实例上,所以实例就不符合接口 
   age:number;
  constructor(name:string,age:number){
      //   this.name = name 
     this .age =  age
  }
} 

 

接口继承类

接口可以继承一个类,当接口继承了该类后,只继承成员和成员类型,不包括实现。

 class Point{
  x:number;
  y:number;
}

interface Point3d extends Point{
  z:number
}

const point3d:Point3d  = {x: 3, y: 4, z: 5}

 

接口还能继承类中被 private 和 protected 修饰的成员,当接口继承的这个类中包含这两个修饰符修饰的成员时,这个接口只可被这个类或他的子类实现。

 class A{
  protected name:string;
}

interface I extends A{}

class B implements I{
  name:string;   //   error, 属性“name”受保护,但类型“B”并不是从“A”派生的类 
 }

class C extends A implements I{
  name:string;
} 

 

 

查看更多关于typescript中的类与接口的关系的详细内容...

  阅读:61次