ready
论坛版主
论坛版主
  • UID24
  • 粉丝0
  • 关注0
  • 发帖数433
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:667回复:0

ts中的interface与type的区别

楼主#
更多 发布于:2024-07-26 12:37
1.组合方式:interface使用extends来实现继承,type使用&来实现联合类型



typy A = {
    a:string
}
type B = {
    b:string
}&A

const a: B = {
    a:'hi'
    b:'hi'
}
interface A = {
    aa:string
}
interface B extends A = {
    bb:string
}
const aa: B = {
    aa:"hi"
    bb:"hi"
}

2.扩展方式:interface可以重复声明来扩展,type一个类型只能申明一次


interface A = {
    a:string
}
interface A = {
   b:string
}
//这里的A就会是
{
    a:string
    b:string
}

//但是type不能
type A = {
    a:string
}
type A = {//这里会报错
        b:string
}





3.范围不同:type适用于基本类型,interface一般不行


type A = string//可以

interface A = string //不可以


4.命名方式不一样: interface 会创建一个新的类型,type只是给类型起一个别名而已


5.typeof 的类型别名可以用于其他的类型,比如 联合类型、元组类型、基本类型,interface 不行。




6.type 能用 in 关键字,而interface不行。


7.默认导出的方式不同,inerface 支持同时声明,默认导出,而type必须先声明后导出



https://blog.csdn.net/weixin_46831501/article/details/124185072
游客


返回顶部