理解 TypeScript 中接口和类型的区别

439 阅读4分钟

大家好,我是晚天

TypeScript 是由 Microsoft 开发的一种开源的编程语言。它是 JavaScript 的超集,添加了静态类型和其他功能,使代码更为健壮且易于维护。在 TypeScript 中,有两种主要的定义自定义类型的方式:接口和类型。尽管它们在外观上可能相似,但它们之间有一些关键的区别。在本文中,我们将讨论 TypeScript 中接口和类型之间的区别并给出具体代码示例。

接口(interface)

interface 是一种定义复杂类型的方式,它可以用来描述对象类型、函数类型、类类型、数组类型、字面量类型等。interface 通常用来描述一个对象的外部形状(Shape),即这个对象有哪些属性、属性的类型是什么、方法的签名是什么等。例如:

interface Person {
  name: string;
  age: number;
  sayHello(): void;
}

class Student implements Person {
  name: string;
  age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  sayHello() {
    console.log(`Hi, my name is ${this.name}, and I'm ${this.age} years old.`);
  }
}

const student = new Student('Tom', 20);
student.sayHello(); // Hi, my name is Tom, and I'm 20 years old.

上面的代码中,我们定义了一个 Person 接口,它包含 name 和 age 属性以及 sayHello 方法。然后我们定义了一个 Student 类,它实现了 Person 接口,因此必须实现 name、age 和 sayHello。在 sayHello 方法中,我们使用模板字符串输出学生的姓名和年龄。

类型(type)

type 是一种定义简单类型的方式,它可以用来定义基本类型、联合类型、交叉类型、字面量类型等。type 可以给一个类型起一个别名,以便重复使用。例如:

type Status = 'active' | 'inactive';

type Person = {
  name: string;
  age: number;
  status: Status;
};

上面的代码定义了一个 Status 类型和一个 Person 类型。Status 类型是一个字符串字面量类型,它只能是 'active' 或 'inactive' 中的一个。Person 类型描述了一个人对象的形状,包括 name 属性、age 属性和 status 属性,其中 status 属性的类型是 Status。

虽然 interface 和 type 在定义类型时有些不同,但在使用时它们是具有一定通用性的。例如,我们可以使用 interface 定义函数的参数类型和返回值类型,也可以使用 type 定义同样的类型,例如:

interface Sum {
  (a: number, b: number): number;
}

type Multiply = (a: number, b: number) => number;

上面的代码分别使用 interface 和 type 定义了一个加法函数类型 Sum 和一个乘法函数类型 Multiply,它们都接受两个参数并返回它们的运算结果。

interface vs type

  • 接口可以被继承,而类型不能。

接口可以通过 extends 关键字来扩展基础接口,例如:

interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  company: string;
}

const employee: Employee = { name: 'John', age: 30, company: 'Acme Inc.' };

类型不能被继承。

  • 类型只能定义一次,而接口可以定义多次并且会自动合并。

类型可以定义一次,例如:

type Status = 'active' | 'inactive';

const status: Status = 'active';

如果试图再次定义同名类型,则会报错。

接口可以定义多次,并且会自动合并同名属性,例如:

interface Person {
  name: string;
}

interface Person {
  age: number;
}

const person: Person = { name: 'John', age: 30 };
  • 接口可以定义可选属性和只读属性,而类型不能。

接口可以定义可选属性和只读属性,例如:

interface Person {
  name: string;
  age?: number;
  readonly email: string;
}

const person1: Person = { name: 'John', email: 'john@example.com' };
const person2: Person = { name: 'Jane', age: 25, email: 'jane@example.com' };

person1.email = 'jane@example.com'; // Error: Cannot assign to 'email' because it is a read-only property.

类型不能定义可选属性和只读属性。

  • 类型可以定义联合类型和交叉类型,而接口不能。

类型可以用联合类型和交叉类型来组合多个类型,例如:

type Person = { name: string } & { age: number };
type Status = 'active' | 'inactive';
type UserStatus = { status: Status } & Person;

const userStatus: UserStatus = { name: 'John', age: 30, status: 'active' };
  • 接口可以定义索引签名,而类型不能。

接口可以定义索引签名,例如:

interface Dictionary {
  [key: string]: number;
}

const dict: Dictionary = { a: 1, b: 2 };

类型不能定义索引签名。

结论

  • 在对象扩展情况下,interface 使用 extends 关键字,而 type 使用交叉类型(&)。
  • 同名的 interface 会自动合并,并且在合并时会要求兼容原接口的结构。
  • interface 与 type 都可以描述对象类型、函数类型、Class 类型,但 interface 无法像 type 那样表达元组、一组联合类型等等。
  • interface 无法使用映射类型等类型工具,也就意味着在类型编程场景中我们还是应该使用 type 。

interface 就是描述对象对外暴露的接口,其不应该具有过于复杂的类型逻辑,最多局限于泛型约束与索引类型这个层面。而 type alias 就是用于将一组类型的重命名,或是对类型进行复杂编程。