接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。
有了接口,在编码方面就更加规范了。以前在写后端(C#)的时候,有时就是先定义好接口,然后再对接口进行实现。有时是大佬把接口定义好,让我去实现具体的功能。这样子,也起到了很好的约束作用。

TypeScript使用方式

TypeScript 接口定义如下:

interface interface_name { 
}

实现接口方式:

const concreteObject: interface_name = {
}

代码示例:

interface IPerson {
name: string,
age: number | string,
print: () => void;
}

const student:IPerson = {
name: 'zzh',
age: 18,
print: () => console.log('print method'),
}

console.log('student object:');
console.log(`student name: ${student.name}`);
console.log(`student age: ${student.age}`);
console.log(`student print method:`);
student.print();




《TypeScript》 - 接口_前端


测试结果


接口与数组



《TypeScript》 - 接口_前端_02


接口继承

接口继承就是说接口可以通过其他接口来扩展自己。
Typescript 允许接口继承多个接口。
继承使用关键字 extends。
单接口继承语法格式:

Child_interface_name extends super_interface_name

多接口继承语法格式:

Child_interface_name extends super_interface1_name, super_interface2_name,…,super_interfaceN_name

代码示例:

interface IAnimal {
age:number,
}

interface IPerson {
height: number,
}

// 单继承实例
interface IStudent extends IPerson {
score: number,
}

let s = <IStudent>{};
s.score = 100;
s.height = 172;
console.log(s.score); // 18

interface ITeacher extends IPerson, IAnimal {
subject: string
}

let t : ITeacher = {
age: 35,
height: 172,
subject: 'Math'
}

console.log(t.age); // 35