interface 和 type 到底有什么区别?

发布于 2021-01-11 17:29:16
关注者
0
被浏览
272
2 个回答
  • Yvan、
    Yvan、 2022-02-23

    type 可以,interface 不行
    1.声明基本类型别名,联合类型,元组等类型。

    type Name = string                              // 基本类型
    
    type arrItem = number | string                  // 联合类型
    
    const arr: arrItem[] = [1,'2', 3]
    
    type Person = { 
      name: Name 
    }
    
    type Student = Person & { grade: number  }       // 交叉类型
    
    type Teacher = Person & { major: string  } 
    
    type StudentAndTeacherList = [Student, Teacher]  // 元组类型
    
    const list:StudentAndTeacherList = [
      { name: 'lin', grade: 100 }, 
      { name: 'liu', major: 'Chinese' }
    ]
    

    2.使用 typeof 获取实例的 类型进行赋值。

    // 当你想获取一个变量的类型时,使用 typeof
    let div = document.createElement('div');
    type B = typeof div
    

    interface 可以,type 不行
    interface 能够声明合并。

    interface Person {
        name: string
    }
    
    interface Person {         // 重复声明 interface,就合并了
        age: number
    }
    
    const person: Person = {
        name: 'lin',
        age: 18
    }
    

    interface 和 type 被typescript设计出来,是完全不同的东西,有各自的职责。interface 是接口,用于描述一个对象。type 是类型别名,用于给各种类型定义别名,让 TS 写起来更简洁、清晰。

  • 面试哥
    面试哥 2021-01-12
    为面试而生,有面试问题,就找面试哥。

    interface 和 type 到底有什么区别?

    作者:rottenpen

知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看