【TS】TypeScript 类型定义之联合类型(union types)和交叉类型(intersection types)

你提供的代码是 TypeScript 中的一种类型定义,它使用了联合类型(union types)和交叉类型(intersection types)。让我们逐步解析这个定义:

基础类型

首先,假设你已经定义了一个基础类型 baseSection,例如:

typescript 复制代码
type baseSection = {
  id: string;
  title: string;
};

联合类型和交叉类型

接下来是类型定义 SectionItem

typescript 复制代码
type SectionItem = baseSection &
  (
    | {
        type: "doc";
        icon: string;
      }
    | {
        type: "card";
        desc: string;
        img: string;
      }
  );

这个定义可以拆解为以下部分:

  1. 交叉类型(Intersection Type)
    baseSection & (...) 表示 SectionItem 类型必须同时拥有 baseSection 类型的属性和括号内的联合类型之一的属性。

  2. 联合类型(Union Type)

    括号内的部分定义了一个联合类型:

    typescript 复制代码
    {
      type: "doc";
      icon: string;
    }
    |
    {
      type: "card";
      desc: string;
      img: string;
    }

    这意味着 SectionItem 可以是以下两种类型之一:

    • 一个对象,包含 type"doc"icon 属性。
    • 一个对象,包含 type"card"descimg 属性。

组合在一起

将交叉类型和联合类型组合在一起,SectionItem 类型必须包含 baseSection 的属性,同时根据 type 的不同,还必须包含特定的附加属性。

具体来说:

  • 如果 type"doc",那么 SectionItem 必须包含 baseSection 的属性以及 icon 属性。
  • 如果 type"card",那么 SectionItem 必须包含 baseSection 的属性以及 descimg 属性。

示例

以下是两个有效的 SectionItem 类型的对象示例:

typescript 复制代码
const docItem: SectionItem = {
  id: "1",
  title: "Documentation",
  type: "doc",
  icon: "doc-icon.png"
};

const cardItem: SectionItem = {
  id: "2",
  title: "Card",
  type: "card",
  desc: "This is a card description.",
  img: "card-image.png"
};

总结

这种写法在 TypeScript 中非常有用,它允许你定义复杂的对象类型,确保对象必须包含某些基础属性,同时根据某个属性的值(如 type)来包含不同的附加属性。这种类型定义方式可以提高代码的类型安全性和可读性。

相关推荐
理智的煎蛋19 小时前
MySQL高可用架构:MHA
linux·数据库·mysql·架构·可用性测试
zz-zjx20 小时前
进程与线程详解, IPC通信与RPC通信对比,Linux前台与后台作业
linux·网络协议·rpc
大筒木老辈子21 小时前
Linux笔记---计算机网络概述
linux·笔记·计算机网络
漂流瓶jz1 天前
解锁Babel核心功能:从转义语法到插件开发
前端·javascript·typescript
keep__go1 天前
postgresql9.2.4 跨版本升级14.6
linux·运维·数据库·postgresql
深思慎考1 天前
LinuxC++项目开发日志——高并发内存池(1-定长内存池)
linux·c++
川石课堂软件测试1 天前
Oracle 数据库如何查询列
linux·数据库·sql·功能测试·oracle·grafana·prometheus
一支鱼1 天前
leetcode-6-正则表达式匹配
算法·leetcode·typescript
光电的一只菜鸡1 天前
ubuntu之坑(十九)——VMware虚拟机扩容磁盘
linux·数据库·ubuntu
岚天start1 天前
网络计算工具ipcalc详解
linux·运维·网络·网关·广播地址·掩码·ipcalc