如何在 TypeScript 中定义接口?-- TypeScript 入门教程





5.00/5 (3投票s)
今天,在本 TypeScript 教程中,我们将学习如何在 TypeScript 中使用接口。请继续阅读以了解更多信息。
TypeScript 中的接口仅包含方法和属性的声明,而不包含实现。 实现接口中所有成员的责任在于实现该接口的类。
今天,在本 TypeScript 教程中,我们将学习如何在 TypeScript 中使用接口。请继续阅读以了解更多信息。
实现接口的类
就像 C# 和 Java 一样,你可以通过实现接口为类创建契约。接口定义了类的 public
属性和方法。它没有任何 private
成员,并且不应包含其成员的任何实现。
在 TypeScript 中,你可以使用关键字 interface
定义接口,如下所示。默认情况下,接口中的所有成员都是 public
的。
interface Person {
fullName: string;
toString();
}
定义接口后,你可以通过以下约定在类中实现它:class [ClassName] implements [InterfaceName]
。 让我们创建两个名为 Employee
和 Customer
的类,它们实现 Person
接口
class Employee implements Person {
empID: string;
fullName: string;
constructor (eID: string, name: string) {
this.empID = eID;
this.fullName = name;
}
toString() {
console.log(`EMP ID of ${fullName}: ${empID}`);
}
}
class Customer implements Person {
custID: string;
fullName: string;
constructor (cID: string, name: string) {
this.custID = cID;
this.fullName = name;
}
toString() {
console.log(`Customer ID of ${fullName}: ${custID}`);
}
}
让我们创建类的实例。由于 Employee
和 Customer
对象都是 Person
类型,让我们这样创建它们
let employee: Person = new Employee("E001", "Kunal");
let customer: Person = new Customer("C001", "");
让我们调用这两个实例的 toString()
方法,并观察它如何在屏幕上打印 person
详细信息
employee.toString(); // prints employee details
customer.toString(); // prints customer details
接口扩展另一个接口
在 TypeScript 中,你还可以从另一个接口扩展一个接口。 这允许你将一个接口的成员复制到另一个接口中。 因此,通过将你的接口分离成可重用的组件,可以实现更大的灵活性。 例如,TwoWheeler
接口扩展 Vehicle
接口,如下所示
interface Vehicle {
}
interface TwoWheeler implements Vehicle {
}
在 TypeScript 中,一个接口还可以扩展多个接口。 例如,让我们看下面的代码,其中 TwoWheeler
接口扩展了 Vehicle
和 Engine
接口
interface Vehicle {
}
interface Engine {
}
interface TwoWheeler extends Vehicle, Engine {
}
接口扩展类
TypeScript 允许你从类类型扩展接口。在这种情况下,类的成员声明将被继承到接口中,但它们的实现不会被继承。 这就像一个类从接口继承一样。
class Vehicle {
constructor (public brand: string) { }
getBrandName() {
return brand;
}
}
class Engine {
constructor (public manufacturer: string) { }
getManufacturerName() {
return manufacturer;
}
}
interface TwoWheeler extends Vehicle, Engine {
getBrandName();
getManufacturerName()
}
简单来说,你可以创建一个扩展类的接口,然后可以在另一个类或接口中实现它。
摘要
因此,今天我们学习了如何使用关键字 interface 定义接口,如何在类中实现接口,如何从另一个接口扩展接口以及如何在接口中扩展类。
如果你来自 C# 或 Java 背景,接口扩展类在 TypeScript 中对你来说是新的。 希望你喜欢这个教程。 不要忘记查看我 TypeScript 教程系列中的其他帖子。 你可以在下面找到链接。