这是一个关于接口和类型的用途以及它们之间的区别的简短教程。
类型和接口都是用来描述自定义类型的设计,但有一些区别。什么是typecript中的接口?
typescript中的接口为类提供了契约和规则来实现它。
它被用来对属性进行分组以创建一个自定义类型。
让我们来创建一个接口
class shape{
length:number;
width:number
}
接口在typescript中有助于
- 创建一个类的对象
- 促进了面向对象的设计
- 允许类型安全
- 可以被其他类实现什么是typescript中的类型?
在typescript中,我们有不同的原始类型,如字符串、数字、布尔值。
如果我们想用这些类型创建一个自定义类型,可以使用类型别名。
例如,如果你声明一个变量是多种类型的联合体,如数字、布尔、字符串、空或未定义。
type CustomType= number|string|boolean |null |undefined
类型脚本中的类型帮助
- 当你想把多种类型当作单一类型时
- 如果你有多个类型的自定义对象,这就很难读懂,也很简单。
接口和类型别名之间的区别?
让我们看看接口和类型在typescript中的区别。
接口可以被合并,但别名不能被合并
例如,我们定义了两个同名的接口Shape ,但成员不同。
interface Shape {
length: number;
breadth: number;
};
interface Shape {
color: string;
};
Typescript合并了两个接口的成员变量并接受了两个属性,如下所述
const shape: Shape = {
length: 5,
breadth: 10,
color:"red"
};
对于类型别名,下面的代码会出现重复标识符 "Shape "的编译错误。
type Shape = {
length: number;
breadth: number;
};
type Shape = {
color: string;
};
合并类型以及类型
对于接口,不可能通过组合多个接口来创建一个新的接口。
interface Shape1 {
length: number;
breadth: number;
};
interface Shape2 {
color: string;
};
可以通过组合多个接口来创建一个类型。
type Shape =Shape1 & Shape2 // valid
对于接口来说,这是不可能的。
interface Shape =Shape1 & Shape2 // not valid
对于类型,可以使用&操作符来组合不同的类型。
type Shape1 = {
length: number;
breadth: number;
};
type Shape2 = {
color: string;
};
type Shape =Shape1 & Shape2
接口和类型的联合
Typecript中的联合允许用OR条件结合多个类型。
对于接口,不可能用多个接口的联合创建一个新的接口。
interface Shape1 {
length: number;
breadth: number;
};
interface Shape2 {
color: string;
};
可以通过多个接口的联合来创建一个类型。
type Shape =Shape1 | Shape2 // valid
对于接口来说,这是不可能的。
interface Shape =Shape1 | Shape2 // not valid
对于类型,可以使用联合运算符来组合不同的类型。
type Shape1 = {
length: number;
breadth: number;
};
type Shape2 = {
color: string;
};
type Shape =Shape1 | Shape2
| 接口 | 类型别名 |
|---|---|
| 接口允许创建一个新的名字 | 不允许创建一个新的名字 |
| 接口可以被扩展或实现 | 类型不能扩展 |
| 接口可以被合并 | 不能合并 |
| 接口描述的是对象、原始类型和类。 | 类型描述的是原始类型 |
| 接口可以通过添加属性来扩展 | 不可能添加新的属性 |
| 接口没有联合或交叉,图元 | 类型可以使用联盟、图元和交集 |