交叉类型:将多个类型合并为一个类型,使用&符号连接。
type AProps = { a: string }type BProps = { b: number }type allProps = AProps & BPropsconst Info: allProps = {a: '小月月',b: 7}
我们可以看到交叉类型是结合两个属性的属性值,那么我们现在有个问题,要是两个属性都有相同的属性值,那么此时总的类型会怎么样?
1、同名基础属性合并
type AProps = { a: string, c: number }type BProps = { b: number, c: string }type allProps = AProps & BPropsconst Info: allProps = {a: '小月月',b: 7,c: 1, // error (property) c: neverc: 'Domesy', // error (property) c: never}
我们在Aprops和BProps中同时加入c属性,并且c属性的类型不同,一个是number类型,另一个是string类型。现在结合为 allProps 后呢? 是不是c属性是 number 或 string 类型都可以,还是其中的一种?
然而在实际中, c 传入数字类型和字符串类型都不行,我们看到报错,显示的是 c的类型是 never。这是因为对应 c属性而言是 string & number,然而这种属性明显是不存在的,所以c的属性是never。
2、同名非基础属性合并
interface A { a: number }interface B { b: string }interface C {x: A}interface D {x: B}type allProps = C & Dconst Info: allProps = {x: {a: 7,b: '小月月'}}console.log(Info) // { x: { "a": 7, "b": "小月月" }}
对于混入多个类型时,若存在相同的成员,且成员类型为非基本数据类型,那么是可以成功合。
interface A { b: number }interface B { b: string }interface C {x: A}interface D {x: B}type allProps = C & Dconst Info: allProps = {x: {a: 7,b: '小月月' //此时b为never类型这里会报错}}
如果 接口A 中的 也是 b,类型为number,就会跟同名基础属性合并一样,此时会报错!