zoukankan      html  css  js  c++  java
  • type和interface的区别

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

    // 基本类型别名
    type Name = string
    
    // 联合类型
    interface Dog {
        wong();
    }
    interface Cat {
        miao();
    }
    
    type Pet = Dog | Cat
    
    // 具体定义数组每个位置的类型
    type PetList = [Dog, Pet]

    2. type 语句中可以使用 typeof 获取类型实例

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

    3. type 支持类型映射,interface不支持

    type Keys = "firstname" | "surname"
    
    type DudeType = {
      [key in Keys]: string
    }
    
    const test: DudeType = {
      firstname: "Pawel",
      surname: "Grzybek"
    }
    
    // 报错
    //interface DudeType {
    //  [key in keys]: string
    //}

    4. interface能够声明合并,type不能

  • 相关阅读:
    继承作业0920
    类与对象
    类和对象基础题
    类和对象数组
    数组
    字符串
    2.1面向对象
    7.1 Java集合概述
    Java动态代理的两种实现方法
    18.5.2动态代理和AOP
  • 原文地址:https://www.cnblogs.com/mengff/p/12936795.html
Copyright © 2011-2022 走看看