TS 接口 interface

242 阅读1分钟

接口 interface

接口只定义对象的结构,而不考虑实际值

接口中所有方法都是抽象方法、接口中所有的属性都不能有实际的值,如:

 interface dog{
     name:string,
     age:number
     sayhello():void
 }

实现接口

定义类,去实现接口, implements关键字

接口定义了标准, 是对类的限制

 interface dog{
     name:string,
     age:number
     sayhello():void
 }
 ​
 class xiaodog implements dog{
     name: string;
     age: number;
     constructor(name:string,age:number) {
         this.name = name,
         this.age = age
     }
     sayhello(): void {
         console.log("hello");
     }
 }
 const dogg = new xiaodog("树叶", 5);
 console.log(dogg);
 dogg.sayhello();
 ​