type和interface有什么区别

在 TypeScript 中,typeinterface 都可以用于定义类型,但它们有一些不同之处和适用场景。

1. interface

  • 扩展性interface 可以通过声明合并被多次声明,并自动合并到一个接口中。
  • 实现:类可以通过 implements 关键字来实现一个接口。
  • 仅用于对象类型:接口主要用于定义对象的形状,虽然支持索引签名等其他一些功能,但主要目的是描述对象。

2. type

  • 灵活性type 可以表示几乎任何类型,包括原始类型、联合类型、交叉类型、元组等。
  • 不可扩展:相同的 type 名称不可以多次声明。

相似点

  • 都可以用来描述对象的形状。
  • 都可以用泛型。

示例

使用 interface

interface Point {
    
    
  x: number;
  y: number;
}

interface Point {
    
    
  z: number; // 合并到上面的接口
}

class MyPoint implements Point {
    
    
  x = 1;
  y = 2;
  z = 3;
}

使用 type

type Point = {
    
    
  x: number;
  y: number;
};

type UserStatus = 'active' | 'inactive' | 'banned';

总结

  • 如果你想定义对象的形状,并可能需要多次扩展或由类实现,那么使用 interface
  • 如果你需要定义联合类型、交叉类型、元组等更复杂的类型,或者不想允许扩展,那么使用 type

在许多情况下,typeinterface 都可以使用,选择哪一个主要取决于你的具体需求和编码风格。

猜你喜欢

转载自blog.csdn.net/m0_57236802/article/details/132174397