您的位置:首页 > 教育 > 锐评 > TypeScript中的交叉类型

TypeScript中的交叉类型

2024/10/7 6:41:54 来源:https://blog.csdn.net/gkx19898993699/article/details/140332167  浏览:    关键词:TypeScript中的交叉类型

        交叉类型:将多个类型合并为一个类型,使用&符号连接。

    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}

        我们在ApropsBProps中同时加入c属性,并且c属性的类型不同,一个是number类型,另一个是string类型。现在结合为 allProps 后呢? 是不是c属性numberstring 类型都可以,还是其中的一种?

        然而在实际中, 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,就会跟同名基础属性合并一样,此时会报错!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com