美文网首页js css html
TS-3 type 和 interface

TS-3 type 和 interface

作者: RickyWu585 | 来源:发表于2023-03-10 18:06 被阅读0次
  • type是类型别名,并不是真正的类型
  • type 声明一个带属性的函数:
type FnWithProps = {
  (a:number,b:number): number,
  props: string
}

const fn: FnWithProps = (a,b) => a+b
fn.props = 'xxx'
  • interface是声明一个接口描述对象的属性
interface X {
  age: number
}

type A1 = Array<string> & {
  name: string
} & X

等同于

interface A2 extends Array<string>,X {
  name: string
}
  • interface描述函数
interface FnWithProp {
(a:number,b:number): number
prop?: string
}

const fn:Fn = (a,b) => a+b
fn.prop = 'xxx'
  • interface 描述日期,类型里不能添加属性了
interface D extends Date {}

const date: D = new Date()
  • type不可以重新赋值
  • interface可以重新赋值

总结区别:

  1. type是类型别名,并不是真正的类型,interface是类型声明,具有真实效果
  2. type可以描述任何类型,interface只针对对象
  3. type不可以重复声明,interface可以重复声明,会自动合并,即可以扩展,比如在axios中扩展config的配置参数类型。因此写的时候一般用interface方便扩展;自己项目的时候一般用type,防止被篡改
  4. type交叉类型功能类似于interface的继承
  5. type功能相对来说更强大,工具类型都是用type来实现的

相关文章

  • Typescript 中的 interface 和 type 的

    interface VS type 大家使用 typescript 总会使用到 interface 和 type,...

  • 集合

    typeScript interface和type的区别interface 和 type 很相似,很多时候,用两种...

  • 看看TypeScript中interface和type间的区别(

    interface和type的区别是什么?本篇文章就来对比一下TypeScript中interface和type,...

  • interface接口

    1、 interface和type类似,区别:interface定义对象形式,不可以定义变量形式,type可以,能...

  • ts 学习笔记

    1、interface和type的区别 interface可定义多次,对象会被合并;type不允许重复定义 int...

  • 浅谈 interface 和 type

    type 类型别名 给类型起一个新名字,当声明非对象类型时适用 支持传入泛型常用的工具方法都是通过 type 实现...

  • type && interface

    //联合类型let num:number|stringnum = 8num = '123'num = 90num....

  • type interface

    TS在声明的时候进行严格检查,赋值的时候比较松 type:类型别名 声明函数:可以单独声明一个函数,也可以声明一个...

  • interface 和 type aliases 区别

    TypeScript interface vs type aliases 在大多数情况下,interface和类型...

  • 2018-12-13 Typescript Types VS I

    typescript types 和 interface 用法相同点和不同点整理 Interface 和 Type...

网友评论

    本文标题:TS-3 type 和 interface

    本文链接:https://www.haomeiwen.com/subject/kexukdtx.html