TS中interface和type 定义类型的区别

ts中定义对象类型常用的interface和type有什么区别呢??看看如下解析.

1.用interface 接口名{属性名:类型},

继承:interface 子 extends 父 { 新增的属性名:类型 }

interface News {
  // 补齐你的代码
  code: number
  msg: string
  data?: {
    title: string
    content: string
  }
}
const news1: Viewnews = {
  code: 200,
  msg: 'success',
  // data: {
  //   title: '当我想明白这件事之后',
  //   content: '20年前,少年误入歧途....',
  // },
  price: 100,
  total: 200
}
// 子继承父的所有属性类型,添加另外的属性类型即可
interface Viewnews extends News {
  price: number
  total: number
}

2.type 类型别名 ={属性名:类型}

继承:type 子 = 父 & { 新增的属性名:类型 }

// 正常的商品
type goodItem = {
  id: number;
  name: string;
  price: number;
  imgUrl?: string;
}

// 打折的商品:正常商品 + newPrice + effectDate 继承
type goodItemDiscount = goodItem & {
  newPrice: number
  effectDate: Date
}

 这样使用起来就明白很多了.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值