基本概念:typeinterface 究竟是啥?

type

type 就是类型别名,用来给各种类型起个名字。可以是基本类型、对象类型、联合类型、交叉类型、元组等。

 1type Name = string;
 2type ID = number | string;
 3type Point = { x: number; y: number };
 4type PointArray = [number, number];

interface

interface 则专注于定义对象的结构和行为。它更像是面向对象编程中的蓝图,描述了对象应该拥有哪些属性和方法。

 1interface Person {
 2  name: string;
 3  age: number;
 4}
 5
 6interface Employee extends Person {
 7  employeeID: number;
 8}

用途和功能:什么时候用 type,什么时候用 interface

type 的用途和功能

  • 复杂类型组合type 非常适合定义联合类型、交叉类型和元组。
  • 灵活性高:可以进行类型变换,比如条件类型和映射类型。
 1type UnionType = string | number | boolean;
 2type Point = { x: number; y: number };
 3type PartialPoint = Partial<Point>;

interface 的用途和功能

  • 描述对象结构interface 用来定义对象的形状,尤其是面向对象编程中的类和对象。
  • 支持多重继承:可以通过 extends 关键字扩展一个或多个接口。
  • 接口合并:同名接口会自动合并,方便扩展和维护。
 1interface User {
 2  name: string;
 3  age: number;
 4}
 5
 6interface Admin extends User {
 7  permissions: string[];
 8}

扩展和合并:typeinterface 的不同之处

type 的扩展

  • 交叉类型:用 & 来实现类型的组合。
 1type A = { a: number };
 2type B = { b: number };
 3type AB = A & B;  
  • 无法进行声明合并:如果在不同地方重复定义同一个 type,编译器会报错。

interface 的扩展

  • 多重继承:通过 extends 关键字扩展一个或多个接口。
 1interface A {
 2  a: number;
 3}
 4
 5interface B {
 6  b: number;
 7}
 8
 9interface AB extends A, B {
10  c: number;
11}
  • 接口合并:在不同文件中重复声明同一个接口,TypeScript 会自动合并它们。
 1interface Person {
 2  name: string;
 3}
 4
 5interface Person {
 6  age: number;
 7}
 8
 9
10
11
12
13

实际使用场景:如何选择 typeinterface

使用 type 的场景

  • 定义联合类型、交叉类型或复杂类型组合。
 1type ID = number | string;
 2type Point = { x: number; y: number };
 3type PartialPoint = Partial<Point>;
  • 进行类型变换,例如映射类型。
 1type Readonly<T> = {
 2  readonly [P in keyof T]: T[P];
 3};

使用 interface 的场景

  • 定义对象的形状,尤其是当对象需要在多个地方被扩展时。
 1interface User {
 2  name: string;
 3  age: number;
 4}
 5
 6interface Admin extends User {
 7  permissions: string[];
 8}
  • 需要利用接口合并功能时,通过重复声明接口来扩展对象的属性。

总结

在 TypeScript 中,typeinterface 都可以用来定义对象的形状,但它们在功能和使用场景上各有优势。

  • type 更适合用于复杂类型组合、类型变换,以及定义联合类型、交叉类型和元组。
  • interface 则在描述对象结构、支持多重继承和接口合并方面表现出色,特别适用于面向对象编程中的类和对象。

选择 type 还是 interface,主要取决于具体需求和使用场景。理解这两者的区别,并根据实际情况灵活应用,能让你的代码更加清晰、灵活和易于维护。

个人笔记记录 2021 ~ 2025