Typescript interfaces 和 type 的区别

85 阅读1分钟

1. 继承其他 interface 或者 type

interface 通过关键字 extend 继承其他 interface

type 通过符号 & 继承其他 type

  1. interface

    interface Monkey {
      color: string;
    }
    
    interface Human extends Monkey {
      name: string;
    }
    
    
  2. type

    type Monkey = {
      color: string;
    }
    type Human = {name: string} & Monkey;
    

2. interface 被设计为 open,type 被设计为 closed

interface 可以重复声明

type 不可以被重复声明

  1. interface example

    interface Monkey {
      color: string;
    }
    interface Monkey {
      name: string;
    }
    
  2. type example

    type Human = {
      color: string;
    }
    
    // error
    type Human = {
      name: string;
    }
    

参考

stackoverflow.com/questions/3…