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

相关推荐

  1. TypeScript交叉类型

    2024-07-12 05:40:04       29 阅读
  2. TypeScript数组类型

    2024-07-12 05:40:04       28 阅读
  3. TypeScript什么是类类型接口?

    2024-07-12 05:40:04       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 05:40:04       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 05:40:04       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 05:40:04       57 阅读
  4. Python语言-面向对象

    2024-07-12 05:40:04       68 阅读

热门阅读

  1. CUDA编程 - asyncAPI 学习记录

    2024-07-12 05:40:04       24 阅读
  2. Postman脚本炼金术:高级数据处理的秘籍

    2024-07-12 05:40:04       25 阅读
  3. 使用SOAP与TrinityCore交互(待定)

    2024-07-12 05:40:04       27 阅读
  4. 编程语言如何和计算机交互:深入解析交互机制

    2024-07-12 05:40:04       25 阅读
  5. LLM_入门指南(零基础搭建大模型)

    2024-07-12 05:40:04       25 阅读
  6. 爬虫学习前记----Python

    2024-07-12 05:40:04       27 阅读
  7. WEB DEVELOPMENT AND APPLICATIONSB DW4213

    2024-07-12 05:40:04       25 阅读
  8. 漏侧bug解决策略

    2024-07-12 05:40:04       22 阅读
  9. C++开篇

    2024-07-12 05:40:04       29 阅读
  10. python图形用户界面和游戏开发_day010

    2024-07-12 05:40:04       26 阅读
  11. v-bind指令——03

    2024-07-12 05:40:04       27 阅读