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
}
这样使用起来就明白很多了.