【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)来包含不同的附加属性。这种类型定义方式可以提高代码的类型安全性和可读性。

相关推荐
ch_09186 小时前
从0构建SDK第4节:实现 ReflectionAgent 的自我反思循环
typescript·agent·ai编程
飞天狗7 小时前
TypeScript类型系统其实是个图灵完备的语言
面试·typescript
天平16 小时前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
orion572 天前
Missing Semester Class1:course overview and introduction of shell
linux
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
ch_09182 天前
从0构建SDK第3节:实现 ReActAgent 的推理与行动循环
typescript·llm·agent
疯狂的魔鬼2 天前
一套 Schema 驱动四视图:记 useCrudSchemas 的设计与实践
前端·javascript·typescript
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698032 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
七歌杜金房3 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac