本文内容如下
泛型函数重载 + 交叉类型 + 类型断言
如果你都有了答案,可以忽略本文章,或去TS学习地图寻找更多答案
简单例子
将两个对象的属性合并
type objType1 = {
name: string, age: number }
type objType2 = {
name: string, age: number, phone: number }
let obj1: objType1 = {
name: 'tao', age: 18 }
let obj2: objType2 = {
name: 'zhou', age: 19, phone: 1234 }
let result = {
}
result as objType1 & objType2
let arr = [obj1, obj2]
arr.forEach((obj: object) => {
Object.keys(obj).forEach((key) => {
if (!result.hasOwnProperty(key)) {
result[key] = obj[key]
}
})
})
用函数实现
interface Button {
btnType: string
text: string
}
interface Link {
alt: string
href: string
}
interface Href {
linkType