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不能

  • 相关阅读:
    【Linux】命令——基本命令
    正则表达式
    Letex
    Markdown
    文本编辑器Vim
    【Linux】集群
    【Linux】软件安装
    共线性synteny
    windows触控手势
    【Linux】bin结尾的安装包
  • 原文地址:https://www.cnblogs.com/mengff/p/12936795.html
Copyright © 2011-2022 走看看