对比TypeScript 中 `type` 和 `interface`

在 TypeScript 中,typeinterface 都用于定义类型,但它们在使用场景和功能上存在一些关键区别。以下是它们的详细对比:


1. 基本定义

  • interface

    • 主要用于定义 对象的结构(属性和方法)。
    • 支持 声明合并(多次声明同一接口会自动合并)。
    • 通过 extends 实现继承。
    interface Person {
      name: string;
      age: number;
    }
    
  • type

    • 可以为任何类型(包括原始类型、联合类型、交叉类型等)定义别名。
    • 不支持声明合并。
    • 通过 & 实现交叉类型扩展。
    type Age = number;
    type Person = {
      name: string;
      age: Age;
    };
    

2. 主要区别

特性interfacetype
声明合并✅ 支持❌ 不支持
扩展方式extends 关键字交叉类型 &
适用类型只能定义对象类型可定义任何类型(对象、联合、元组等)
实现类可通过 implements 实现只能实现对象类型的 type
工具提示显示接口名称(更清晰)显示别名展开后的类型(可能冗长)
联合/交叉类型需通过继承组合直接支持联合(`

3. 使用场景

推荐使用 interface
  1. 定义对象类型
interface User {
  id: string;
  name: string;
}
  1. 需要声明合并(如扩展第三方库类型):
interface Window {
  myCustomProp: string;
}
  1. 类实现接口
interface Animal {
  eat(): void;
}
class Dog implements Animal {
  eat() { /* ... */ }
}
推荐使用 type
  1. 定义联合类型
type Result = Success | Failure;
  1. 定义交叉类型
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
  1. 定义元组或复杂类型
type Coordinates = [number, number];
type Callback = (data: string) => void;
  1. 使用条件类型或映射类型
type Nullable<T> = T | null;
type ReadonlyUser = Readonly<User>;

4. 示例对比

扩展类型
  • interface(使用 extends):
    interface Animal { name: string }
    interface Dog extends Animal { breed: string }
    
  • type(使用 &):
    type Animal = { name: string };
    type Dog = Animal & { breed: string };
    
联合类型
  • typeinterface 无法直接实现):
    type ID = string | number;
    

5. 最佳实践

  • 默认使用 interface
    当需要定义对象类型或需要声明合并时,优先使用 interface
  • 使用 type 的场景
    当需要定义联合、交叉类型,或使用高级类型工具(如条件类型、映射类型)时,使用 type

总结

  • interface
    适合定义对象结构,支持声明合并和类实现,代码可读性高。
  • type
    灵活,支持任何类型定义,适合复杂类型操作。

根据具体需求选择合适的关键字,可以使代码更清晰、可维护性更高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值