![](https://i-blog.csdnimg.cn/blog_migrate/a398deea0226832171e8ecb4153c3c54.png)
一、用类实现接口
用类实现接口 implements
用类实现接口 === 用接口对类进行约束
interface IRunning {
// 这个方法没有任何的实现
running(): any
}
interface ISwim {
// 这个方法没有任何的实现
swim(): any
}
1、1个接口约束类
// 类里面必须要有接口的方法
class Man implements IRunning {
running() {
return "running";
}
}
2、多个接口约束类
class Woman implements IRunning, ISwim {
running() {
return "running";
}
// 如果不写swim方法,会报错:类型 "Woman" 中缺少属性 "swim",但类型 "ISwim" 中需要该属性
swim() {
return "swim";
}
}
const man = new Man();
const woman = new Woman();
console.log(man.running()); // running
console.log(woman.swim()); // swim
二、接口继承接口
接口继承接口 extends
// 上面的代码有IRunning接口、ISwim接口,假如还有其他接口,那么可以让接口去继承接口
// 继承后,ISport接口会带上IRunning接口、ISwim接口的方法
interface ISport extends IRunning, ISwim {
// 里面可以什么都不用写,也可以写自己的东西
}
// 然后,用类实现接口时可以这样写
class Child implements ISport {
running() {
}
swim() {
}
}
三、接口继承类
接口继承类 extends
class Foods {
name: string
constructor(name: string) {
this.name = name;
}
getName() {
}
}
// 接口继承类后,会把类的实例属性和实例方法都继承过来
interface IMyFoods extends Foods {
color: string
}
const foods: IMyFoods = { }; // 报错,会提示:类型“{}”缺少类型“IMyFoods”中的以下属性: color, name, getName
// 写成下面这样就可以了:
const foods: IMyFoods = {
color: 'blue',
name: 'tomato',
getName() {
},
}
四、声明合并
1、函数合并(看函数重载)
2、类合并(看接口合并,规则一样,不再详细讲解)
3、接口合并
相同名字的接口如何进行合并:同名属性会合并为一个属性,不同名属性会添加进接口
interface IFood {
name: "鱼",
age: number
}
interface IFood {
// 后续属性声明必须属于同一类型
name: "鱼1" // 报错,属性“name”的类型必须为"鱼",但此处却为类型"鱼1"
name: '鱼', // 正确写法
color: "红色"
}
// 相当于
/*
interface IFood {
name: "鱼",
age: number,
color: "红色"
}
*/
const fish: IFood = {
name: '鱼',
age: 19,
color: "红色"
}