TypeScript 接口
一、特点
1、接口可以被实现,接口不能实例化,没有自己的方法
2、一个类可以实现多个接口
3、接口可以继承接口
3、同名接口可以组合
4、定义类和对象的结构
二、定义类的接口
1、接口不能实例化,没有自己的方法,属性和方法都要被类实现
2、案例
interface PersonInterface{ name:string age:number introduce(sex:string):string } // 实现接口,接口不能实例化,没有自己的方法 class SinglePerson implements PersonInterface{ constructor(public name:string, public age:number){} introduce(sex: string): string { return `大家好,俺叫${this.name},俺今年${this.age}岁了,俺是一个${sex}孩子` } } const p1 = new SinglePerson('jojo', 8) console.log(p1.age); console.log(p1.introduce("男"));
三、接口继承接口
1、接口可以继承接口,类实现接口
2、案例
interface PersonInterface{ name:string, age:number } // 接口继承接口 interface WorkerInterface extends PersonInterface{ money:number info():string } // 类实现接口 class Wk implements WorkerInterface{ constructor(public name:string, public age:number, public money:number){} info(): string { return `${this.name}今年${this.age}岁, 一个月工资${this.money}k` } } let p = new Wk("jojo", 35, 2.8) console.log(p.info());
四、同名接口合并
1、同名接口可以合并
2、案例
interface CarInterface{ brand:string cost:number } // 同名接口 合并 interface CarInterface{ speedMax: number horsepower:number introduce():void } // 类实现接口 class MiCar implements CarInterface{ constructor(public brand:string, public cost:number, public speedMax:number, public horsepower:number){} introduce(): void { console.log(`${this.brand},售价${this.cost}万,最大速度超过${this.speedMax},${this.horsepower}马力`); } } const su7U = new MiCar('su7U', 52, 320, 1500) su7U.introduce()
五、实现多个接口
1、类可以实现多个接口
2、案例
interface AreaInterface{ width:number, heigh:number } interface BrandInterface{ brand:string, } // 实现多个接口 class Table implements AreaInterface, BrandInterface{ constructor(public brand:string, public width:number, public heigh:number ){} introduce(){ console.log(`品牌:${this.brand},面积:${this.heigh * this.width}`); } } const t1 = new Table("源氏木语", 140, 80) t1.introduce()
六、定义对象的结构
1、合并接口
interface CarInterface{ brand:string cost:number } // 同名接口 合并 interface CarInterface{ speedMax: number horsepower:number introduce():void } // 定义对象结构 let car:CarInterface = { brand:"小米", cost:52, speedMax:320, horsepower:1500, introduce(){ console.log(`品牌:${this.brand},价格:${this.cost},最大速度:${this.speedMax},马力:${this.horsepower}`); } } car.introduce()
2、继承接口 定义对象结构
interface PersonInterface{ name:string, age:number } // 继承接口 interface WorkerInterface extends PersonInterface{ money:number, introduce():void } // 实现对象 const coder:WorkerInterface ={ name:'小明', age:35, money:2.8, introduce(){ console.log(`打工人:${this.name},已经${this.age}岁了,薪资${this.money}k`); } } console.log(coder.name); coder.introduce()
3、接口 定义对象结构
// 接口 interface PersonInterface{ name:string, age:number, sex:string, worker?:string } // 实现对象 let p1:PersonInterface = { name:'小美', age:18, sex:"女" } console.log(p1.age); console.log(p1.name);
七、接口和抽象类的区别
1、抽象类被继承,接口被实现
2、抽象类可以有自己的方法,接口不行
3、抽象类 规范类的格式,接口可以规范类和对象的格式
八、type和接口的区别
1、type 自定义类型: 基本类型、组合类型、交叉类型,不支持继承和合并
2、接口支持继承和合并,更专注对象和类的结构