TypeScript 如何从一个类扩展一个接口
在本文中,我们将通过一些编码示例来理解如何在TypeScript中扩展接口。首先,让我们快速了解如何使用以下语法在TypeScript中创建类和接口:
语法:
这是创建类的语法。我们可以使用以下语法在TypeScript中创建类:
class class_name {
...
}
这是创建接口的语法。我们可以使用以下语法在TypeScript中创建一个接口:
interface interface_name {
...
}
现在我们已经理解了创建类和接口的基本语法,让我们通过下面的编码示例了解这些语法以及我们如何从一个类扩展一个接口的主要目标:
示例1:
- 在这个示例中,将定义一个类,并在其中定义一些变量。
- 然后构建一个接口,该接口将扩展上述类,并在接口内定义一个方法,但该方法的定义将在另一个类中进行。
- 然后创建另一个类,该类负责扩展父类以及上述定义的接口。
- 对于这个派生类,将实例化一个对象,并进一步使用该对象来打印在方法内定义的结果,该方法在接口本身中提供了声明。
JavaScript
// Parent class creation
class Person {
public name: string;
}
// Interface extended from the above class
interface Details extends Person {
details(): void;
}
// Using the above illustrated interface and class together
class Person_Details extends Person implements Details {
details(): void {
this.name = "GeeksforGeeks";
console.log(this.name);
}
}
let object = new Person_Details();
object.details();
输出:
GeeksforGeeks
示例2:
- 在此示例中,创建了一个被推断为父类的类,其中包含不同的变量声明。
- 然后,定义了两个接口(或多个接口),每个接口都包含单独的方法声明,这些方法的定义稍后会在一个单独的类(被推断为派生类)中定义。
- 然后创建了一个派生类,负责扩展父类以及定义的接口。
- 最后,实例化一个对象,负责调用在派生类中定义的所有方法,最终得到结果。
Javascript
// Parent class declaration
class Student {
public id: number;
public name: string;
}
// Creating multiple interfaces which
// will extend the above class
interface Student_1 extends Student {
student1_details(): void;
}
interface Student_2 extends Student {
student2_details(): void;
}
// Creating a class which will extend
// the above interfaces
class Student_Details extends Student implements Student_1, Student_2 {
student1_details(): void {
this.name = "Apple";
this.id = 1;
console.log(this.id + " - " + this.name);
}
student2_details(): void {
this.name = "Banana";
this.id = 2;
console.log(this.id + " - " + this.name);
}
}
let student_object = new Student_Details();
student_object.student1_details();
student_object.student2_details();
输出:
1 - Apple
2 - Banana
极客教程