做网站的应用,优秀网站建设最新报价,辽宁网站建设电话,网站开发人员工具种类交叉类型#xff1a;将多个类型合并为一个类型#xff0c;使用符号连接。 type AProps { a: string }type BProps { b: number }type allProps AProps BPropsconst Info: allProps {a: 小月月,b: 7} 我们可以看到交叉类型是结合两个属性的属性值#xff0c;那… 交叉类型将多个类型合并为一个类型使用符号连接。 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就会跟同名基础属性合并一样此时会报错