ts - 接口(interface)和类型别名(type)的区别

接口/类型别名的扩展(继承)

  • 接口(interface)使用extends关键字
interface Animal {
  name: string
}

interface Bear extends Animal{
  honey: boolean
}

const bear: Bear = {
  name: "winie",
  honey: true
}

console.log(bear.name);
console.log(bear.honey);
  • 类型别名(type)使用&符
type Animal = {
  name: string
}

type Bear = Animal & {
  honey: boolean
}

const bear: Bear = {
  name: "winie",
  honey: true
}

向现有的类型添加字段

  • 接口
    接口可以重复声明,每次声明的字段都会追加到相同接口名中
interface My {
  title: string
}

interface My {
  count: number
}

const s: My = {
  title: "123",
  count: 12
}
  • 类型别名
    类型别名不可以重复声明,也不能向已有的类型别名中添加新字段
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值