zoukankan      html  css  js  c++  java
  • TypeScript中type与interface的区别

    虽然很费解TypeScript为何要搞两个差不多的东西,初步看起来,两者除了写法上稍微有点区别,功能上差不多,比如定义一个Person的对象;

    //interface
    interface Person {
      name: string
      age: number
    }
    
    //type
    type Person = {
      name: string
      age: number
    }
    

    但是还是需要弄懂一下,毕竟已经是这样了,稍微记录一下目前的理解;

    关于定义

    interface用于定义一个新的对象的结构跟类型
    type用于给一个已存在的对象取名或者赋予别名

    不同的地方

    • interface可以重复定义一个对象,最终的结果是合集的状态
    interface Person {
      name: string
      age: number
    }
    
    interface Person {
      address: string
    }
    
    type Person2 = {
      name: string
      age: number
    }
    
    type Person3 = Person2 & {
      address: string
    }
    
    • type可以定义联合类型,比如
    type language = 'cn'|'en'|'jp'
    
  • 相关阅读:
    Swagger入门
    UOS
    Java多线程
    英语语法小知识-Unit1
    MVVM
    Vue入门
    Mybatis入门
    Python pip install
    js 触发LinkButton点击事件,执行后台方法
    ajax 请求 ascx
  • 原文地址:https://www.cnblogs.com/fwindpeak/p/14479941.html
Copyright © 2011-2022 走看看