接口(Interface)是 TypeScript 的一个核心概念,它是对行为的抽象,而不是对实现的抽象。
接口一般用于定义对象的形状,即定义对象具有哪些属性和方法。接口能够确保对象遵守一些规定的合同。
接口可以被类实现,它可以定义类应遵循的协议。接口是可选的,意味着不用实现接口的所有成员。
下面是接口的一些基本使用方法:
- 定义接口:
interface IName {
firstName: string;
lastName: string;
}
- 实现接口:
class Person implements IName {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
- 可选属性的接口:
interface IName {
firstName: string;
lastName?: string;
}
- 只读属性的接口:
interface IName {
readonly firstName: string;
lastName: string;
}
- 函数类型的接口:
interface IName {
(firstName: string, lastName: string): string;
}
let buildName: IName = (firstName: string, lastName: string): string => {
return firstName + ' ' + lastName;
}
- 可索引的类型接口:
interface IName {
[index: number]: string;
}
let names: IName = ['John', 'Doe'];
- 继承接口:
interface IName {
firstName: string;
lastName: string;
}
interface IPerson extends IName {
age: number;
}
class Person implements IPerson {
firstName: string;
lastName: string;
age: number;
constructor(firstName: string, lastName: string, age: number) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
- 接口之间的继承:
interface IName {
firstName: string;
lastName: string;
}
interface IPerson extends IName {
age: number;
}
interface IWorker extends IPerson {
job: string;
}
let worker: IWorker = {
firstName: 'John',
lastName: 'Doe',
age: 30,
job: 'Developer'
};
以上就是接口的一些基本使用方法,接口在大型应用中非常有用,可以帮助开发者定义复杂的数据结构和类型。