自学内容网 自学内容网

TypeScript中的交叉类型

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

    type AProps = { a: string }
    type BProps = { b: number }

    type allProps = AProps & BProps

    const Info: allProps = {
        a: '小月月',
        b: 7
    }

        我们可以看到交叉类型是结合两个属性的属性值,那么我们现在有个问题,要是两个属性都有相同的属性值,那么此时总的类型会怎么样?

1、同名基础属性合并

    type AProps = { a: string, c: number }
    type BProps = { b: number, c: string }

    type allProps = AProps & BProps

    const Info: allProps = {
        a: '小月月',
        b: 7,
        c:  1, // error (property) c: never
        c:  '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 & D

    const 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 & D

    const Info: allProps = {
      x: {
        a: 7,
        b: '小月月' //此时b为never类型这里会报错
      }
    }

        如果 接口A 中的 也是 b,类型为number,就会跟同名基础属性合并一样,此时会报错!


原文地址:https://blog.csdn.net/gkx19898993699/article/details/140332167

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!