TypeScript 中的 interface 和 type 有什么区别?
Type和Interface方法都用于描述 TypeScript 中对象的结构。但是拥有一些根据情况会有所帮助的特定功能,在它们之间进行选择并且完全取决于开发人员。
TypeScript 中的类型:TypeScript 中的类型系统描述了该语言支持的不同数据类型。它分为三个主要部分,即Any Type 、 Built-In Type和User-Defined Type 。 TypeScript 中的类型系统负责在将任何值作为输入提供给程序之前检查其数据类型。
例子:
// Creating a type
type Geeks {
name: string;
age: number
}
type Geeks {
email: string;
}
// Using the merged type
const gfg: Geeks = {
name: " kgowda",
age: 20,
email: " kgowda@gmail.com"
};
console.log(gfg);
输出:
"Duplicate identifier 'Geeks'" error.
TypeScript 中的接口: TypeScript 中的接口是所有实体都必须遵循的语法义务。它只能包含成员的声明,并负责定义属性、方法和事件。在某种程度上,它负责定义派生类必须遵循的标准结构。
例子:
// Creating a interface
interface Geeks {
name: string;
age: number
}
interface Geeks {
email: string;
}
// Using the merged interface
const gfg: Geeks = {
name: " kgowda",
age: 20,
email: " kgowda@gmail.com"
};
console.log(gfg);
输出
name: " kgowda", age: 20, email: " kgowda@gmail.com"
TypeScript 中类型和接口的区别:
Type | Interface |
---|---|
It is a collection of data types. | It is a form of syntax. |
It supports the creation of a new name for a type. | It provides a way to define the entities. |
It has less comparatively less capabilities. | It has comparatively more capabilities. |
It does not support the use of an object. | It supports the use of an object. |
Multiple merged declarations cannot be used. | Multiple merged declarations can be used. |
Two types having the same name raise an exception. | Two interfaces having the same name get merged. |
It does not have implementation purposes. | It has an implementation purpose. |