type注解對象類型
在TS中對于對象數據的類型注解,除了使用interface之外還可以使用類型別名來進行注解,作用類似
type Person = {name: stringage: number
}const p:Person = {name: 'lily',age: 16
}
type + 交叉類型&模擬繼承
類型別名配合交叉類型(&)可以模擬繼承,同樣可以實現類型復用
// 父接口
type GoodsType = {id: stringprice: number
}
// 子接口繼承
type DisGoodsType = GoodsType & {disPrice: number
}
let goods:DisGoodsType = {id: '01',price: 99,disPrice: 89
}
console.log(goods.price)
interface 對比 type
1?? 相同點
-
都能描述對象類型
-
都能實現繼承,interface 使用 extends,type 配合交叉類型&
2?? 不同點
-
type 除了能描述對象還可以用來自定義其它類型
-
同名的interface會合并(屬性取并集,不能出現類型沖突),同名type會報錯
在注解對象類型的場景下非常相似,推薦?使用type,type更加靈活
Demo:
type Data = {title: stringcontent: string
}
type ResData = {code: numbermsg: stringdata: Data
}
let res:ReaData = {code: 200,msg:'ok',data: {title:'文章標題',content:'文章內容'}
}console.log(res.data.content)