TypeScript 接口和类的区别
在本文中,我们将看到“接口”和“类”在TypeScript中的区别。
接口: 接口是用于类型检查的虚拟结构。 在TypeScript中,我们使用接口关键字创建具有标识符的新接口。 它为相同数据类型创建了结构。 接口是用于具有名称和类型的对象定义属性和方法的结构。
语法:
interface New_Interface{ // This is interface Body }
特点:
- 它具有松散耦合。
- 支持多重继承。
示例1:
Javascript
// Interface for Class
interface ForClass {
readonly var1:string;
}
let newclass: ForList = {var1:"Interface"};
console.log(newclass);
输出:
{ var1: 'Interface' }
示例2:
Javascript
// Interface for Object with extends function
interface ForObj {
First: string
}
interface forNewObj extends ForObj {
Second: number
}
let newArray: forNewObj = {
First: "Interface for Object",
Second: 2
};
console.log(newArray);
输出:
{ First: 'Interface for Object', Second: 2 }
类: 它们是对象的骨架,通过使用它们,我们实现对象。在TypeScript中,我们使用class关键字来创建对象的构造函数。它可以有属性、方法和变量。
语法:
class geeks {
// Class property and methods
// are created here
}
特点:
- 在类中,它支持成员可见性。
- 它支持成员重写。
- 它支持继承。
示例1:
Javascript
const Table_Object = {
// field of class
Size : 32,
// Collection field
contents : ["Book","Pen"],
// Function
print : function() {
console.log("hello Geeks")
}
}
console.log(Table_Object);
输出:
{
Size: 32,
contents: [ 'Book', 'Pen' ],
print: [Function: print]
}
示例2:
JavaScript
class Geeks {
name : string ;
articles: number ;
cp_problems: number;
// Constructor of class
constructor(name:string, articles: number, cp_problems: number) {
this.name = name;
this.articles = articles;
this.cp_problems = cp_problems;
}
// About object
About() : void {
console.log("Name of Geeks: " + this.name );
console.log("No. of articles by Geeks: "
+ this.articles);
console.log("No. of cp problems sol by Geeks: "
+ this.cp_problems)
}
}
var geek1 = new Geeks("Abhinav", 87, 560);
geek1.About();
输出:
Name of Geeks: Abhinav
No. of articles by Geeks: 87
No. of cp problems sol by Geeks: 560
接口和类之间的区别如下:
| 接口 | 类 |
|---|---|
| 通过使用interface关键字,我们可以创建接口。 即 interface Interface_Name{ \\ Interface Body } | 通过使用class关键字,我们可以创建类。 即 class Class_Name{ \\ Class Body } |
| 接口的蓝图主要是对象的类型结构。即它是只定义参数类型的对象。 | 类是对象的蓝图,即我们如何实现代码中的对象。 |
| 它用于类型检查目的。在TypeScript语言中,接口主要用于检查对象中的参数类型。 | 在TypeScript中,类用于创建对象。它用于实现对象。 |
| 在TypeScript中,我们不能使用new关键字来创建接口的实例。这意味着我们不能在TypeScript中创建实例的副本。 | 在TypeScript中,我们可以使用new关键字创建类的新实例。这意味着我们可以创建类的副本。 |
| 接口是虚拟结构。它只存在于TypeScript代码中,而不存在于TypeScript编译后的JavaScript代码中。 | 在TypeScript编译成JavaScript之后,它始终存在于代码中。 |
极客教程