📅  最后修改于: 2021-01-11 13:04:37             🧑  作者: Mango
TypeScript是一种面向对象的JavaScript语言,支持诸如类,接口,多态性,数据绑定等编程功能。TypeScript支持ES6和更高版本中的这些功能。
类是用于创建可重用组件的基本实体。它是一组具有共同属性的对象。就OOP而言,类是用于创建对象的模板或蓝图。它是一个逻辑实体。
我们可以在类定义中定义以下属性:
字段:它是在类中声明的变量。
方法:它代表对象的动作。
构造函数:它负责初始化内存中的对象。
嵌套的类和接口:这意味着一个类可以包含另一个类。
声明一个类的语法
我们可以使用TypeScript中的class关键字声明一个类。以下语法说明了类声明。
class {
field;
method;
}
要了解更多信息,请单击此处。
接口是在我们的应用程序中充当合同的结构。它定义了要遵循的类的语法,这意味着实现接口的类必须实现其所有成员。我们无法实例化该接口,但是可以由实现它的类对象引用它。
该接口仅包含方法和字段的声明,而不包含实现。我们不能用它来构建任何东西。一个类继承一个接口,而实现接口的类则定义该接口的所有成员。
当Typescript编译器将其编译为JavaScript时,该接口将从JavaScript文件中删除。因此,其目的仅是在开发阶段提供帮助。
接口声明
我们可以使用TypeScript中的interface关键字声明一个接口。以下语法说明了接口声明。
interface interface_name {
// variables' declaration
// methods' declaration
}
接口使用
我们可以使用该界面进行以下操作:
要了解更多信息,请单击此处。
TypeScript Class | TypeScript Interface | |
---|---|---|
Introduction | Classes are the fundamental entities used to create reusable components. It is a group of objects which have common properties. It can contain properties like fields, methods, constructors, etc. | An Interface defines a structure which acts as a contract in our application. It contains only the declaration of the methods and fields, but not the implementation. |
Usage | It is used for object creation, encapsulation for fields, methods. | It is used to create a structure for an entity. |
Keyword | We can create a class by using the class keyword. | We can create an interface by using the interface keyword. |
Compilation | A class cannot disappear during the compilation of code. | Interface completely disappeared during the compilation of code. |
Real-Time Usage | Design Pattern, Designing project Structure | Implements of defined Architectures |
Instantiation | A class can be instantiated to create an object. | An interface cannot be instantiated. |
Methods | The methods of a class are used to perform a specific action. | The methods in an interface are purely abstract (the only declaration, not have a body). |
Access Specifier | The member of a class can be public, protected, or private. | The members of an interface are always public. |
Constructor | A class can have a constructor. | An interface cannot have a constructor. |
Implement/Extend | A class can extend only one class and can implement any number of the interface. | An interface can extend more than one interfaces but cannot implement any interface. |