type 与 interface 的区别,你真的懂了吗?

类型别名 type

首先认识一下什么是类型别名?

类型别名用来给一个类型起个新名字,使用 type 创建类型别名,类型别名不仅可以用来表示基本类型,还可以用来表示对象类型、联合类型、元组和交集。让我们看一些例子:

  1. type userName = string; // 基本类型
  2. type userId = string | number; // 联合类型
  3. type arr = number[];
  4. // 对象类型
  5. type Person = {
  6. id: userId; // 可以使用定义类型
  7. name: userName;
  8. age: number;
  9. gender: string;
  10. isWebDev: boolean;
  11. };
  12. // 范型
  13. type Tree<T> = { value: T };
  14. const user: Person = {
  15. id: "901",
  16. name: "椿",
  17. age: 22,
  18. gender: "女",
  19. isWebDev: false,
  20. };
  21. const numbers: arr = [1, 8, 9];

接口 interface

接口是命名数据结构(例如对象)的另一种方式;与type 不同,interface仅限于描述对象类型。

接口的声明语法也不同于类型别名的声明语法。让我们将上面的类型别名 Person 重写为接口声明:

  1. interface Person {
  2. id: userId;
  3. name: userName;
  4. age: number;
  5. gender: string;
  6. isWebDev: boolean;
  7. }

interface和type的相似之处

在讨论二者区别之前, 首先看一下二者的相似之处(为何开发中,我们觉得用哪个都一样)

都可以描述 ObjectFunction

两者都可以用来描述对象或函数,但语法不同:

Type

  1. type Point = {
  2. x: number;
  3. y: number;
  4. };
  5. type SetPoint = (x: number, y: number) => void;

Interface

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. interface SetPoint {
  6. (x: number, y: number): void;
  7. }

二者都可以被继承

interfacetype 都可以继承。

另一个值得注意的是,接口和类型别名并不互斥。类型别名可以继承接口,反之亦然。只是在实现形式上,稍微有些差别。

interface 继承 interface

  1. interface Person{
  2. name:string
  3. }
  4. interface Student extends Person { stuNo: number }

interface 继承 type

  1. type Person {
  2. name:string
  3. }
  4. interface Student extends Person { stuNo: number }

type 继承 type

  1. type Person{
  2. name:string
  3. }
  4. type Student = Person & { stuNo: number }

type 继承 interface

  1. interface Person{
  2. name:string
  3. }
  4. type Student = Person & { stuNo: number }

实现 implements

类可以实现interface 以及 type(除联合类型外)

  1. interface ICat{
  2. setName(name:string): void;
  3. }
  4. class Cat implements ICat{
  5. setName(name:string):void{
  6. // todo
  7. }
  8. }
  9. // type
  10. type ICat = {
  11. setName(name:string): void;
  12. }
  13. class Cat implements ICat{
  14. setName(name:string):void{
  15. // todo
  16. }
  17. }

上面提到了特殊情况,类无法实现联合类型, 是什么意思呢?

  1. type Person = { name: string; } | { setName(name:string): void };
  2. // 无法对联合类型Person进行实现
  3. // error: A class can only implement an object type or intersection of object types with statically known members.
  4. class Student implements Person {
  5. name= "张三";
  6. setName(name:string):void{
  7. // todo
  8. }
  9. }

上面聊了interfacetype的相似之处, 接下来就来看看他们的区别。

二者区别

1. 定义基本类型别名

type可以定义基本类型别名, 但是interface无法定义,如:

  1. type userName = string
  2. type stuNo = number
  3. ...

2. 声明联合类型

type可以声明联合类型, 例如:

  1. type Student = {stuNo: number} | {classId: number}

3. 声明元组

type可以声明 元组类型

  1. type Data = [number, string];

以上都是 type能做到, 而interface做不到的, 接下来聊聊type做不到的

4. 声明合并

如果你多次声明一个同名的接口,TypeScript 会将它们合并到一个声明中,并将它们视为一个接口。这称为声明合并, 例如:

  1. interface Person { name: string }
  2. interface Person { age: number }
  3. let user: Person = {
  4. name: "Tolu",
  5. age: 0,
  6. };

这种情况下,如果是type的话,重复使用Person是会报错的:

  1. type Person { name: string };
  2. // Error: 标识符“Person”重复。ts(2300)
  3. type Person { age: number }

5. 索引签名问题

如果你经常使用TypeScript, 一定遇到过相似的错误:

Type ‘xxx’ is not assignable to type ‘yyy’

Index signature is missing in type ‘xxx’.

看个例子来理解问题:

  1. interface propType{
  2. [key: string] : string
  3. }
  4. let props: propType
  5. type dataType = {
  6. title: string
  7. }
  8. interface dataType1 {
  9. title: string
  10. }
  11. const data: dataType = {title: "订单页面"}
  12. const data1: dataType1 = {title: "订单页面"}
  13. props = data
  14. // Error:类型“dataType1”不可分配给类型“propType”; 类型“dataType1”中缺少索引签名
  15. props = data1

我们发现dataTypedataType1对应的类型一样,但是interface定义的就赋值失败,是什么原因呢?刚开始百思不解,最后我在 stack overflow上找到了一个相似的问题:

type 与 interface 的区别,你真的懂了吗? - 图1

并且很幸运的找到了有效的答案:

type 与 interface 的区别,你真的懂了吗? - 图2

翻译过来的大致意思就是:

Record<string,string>{[key:string]:string}相同。只有当该类型的所有属性都已知并且可以对照该索引签名进行检查时,才允许将子集分配给该索引签名类型。在您的例子中,从exampleTypeRecord<string,string>的所有内容都是可分配的。这只能针对对象字面量类型进行检查,因为一旦声明了对象字面量类型,就无法更改它们。因此,索引签名是已知的。

相反,在你使用interface去声明变量时,它们在那一刻类型并不是最终的类型。由于interface可以进行声明合并,所以总有可能将新成员添加到同一个interface定义的类型上。

再结合👆第4点 声明合并的讲解, 这样就很好理解了。就是说interface定义的类型是不确定的, 后面再来一个:

  1. interface propType{
  2. title:number
  3. }

这样propType类型就被改变了。

总结

官方推荐用 interface,其他无法满足需求的情况下用 type

但其实,因为 联合类型 和 交叉类型 是很常用的,所以避免不了大量使用 type 的场景,一些复杂类型也需要通过组装后形成类型别名来使用。

所以,如果想保持代码统一,还是可选择使用 type。通过上面的对比,类型别名 其实可涵盖 interface 的大部分场景。

对于 React 组件中 propsstate,使用 type ,这样能够保证使用组件的地方不能随意在上面添加属性。如果有自定义需求,可通过 HOC二次封装。

编写三方库时使用interface,其更加灵活自动的类型合并可应对未知的复杂使用场景。

参考资料:

  • TypeScript: type alias 与 interface