当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/398035.html

相关文章:

  • CNN -1 神经网络-概述2
  • 利用js实现图片压缩功能
  • 2024.7.10 刷题总结
  • ES6 async 函数详解 (十)
  • 【安全设备】入侵检测
  • 07浅谈大语言模型可调节参数tempreture
  • Redis数据同步
  • 快手矩阵源码,快速拥有自己的短视频矩阵
  • notes for datawhale 2th summer camp NLP task1
  • 攻防世界(PHP过滤器过滤)file_include
  • PostGIS2.4服务器编译安装
  • 虚拟机安装Linux CENTOS 07 部署NET8 踩坑大全
  • 【C++】CMake入门
  • 云WAF | 云waf保护你的网络安全
  • c++初阶知识——类和对象(1)
  • Vue 3 组件通信全解:从基础到高级技巧
  • 大众汽车入职SHL在线测评、英语口语、招聘笔试如何通过、考点分析|备考建议
  • 《植物大战僵尸杂交版》2.2:新版本体验与下载指南
  • 7月11日学习打卡,数据结构栈
  • 数据结构第20节 快速排序以及优化
  • 3分钟理解超键、候选键、主键
  • Centos忘记密码,重置root密码
  • Android初学者书籍推荐
  • 安卓文件上传照片单张及多张照片上传实现
  • 小白学webgl合集-import.meta.url 和 new URL() bug
  • pico+unity3d开启彩色透视
  • python常用命令
  • 使用定时器消除抖动
  • IOS热门面试题一
  • 构建LangChain应用程序的示例代码:62、如何使用Oracle AI向量搜索和Langchain构建端到端的RAG(检索增强生成)pipeline