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

相关推荐
Felven7 分钟前
飞腾D2000 GPIO中断调试
linux·gpio·中断·d2000
喵了meme43 分钟前
Linux学习日记21:读写锁
linux·c语言·学习
LYFlied1 小时前
TypeScript 常见面试问题
ubuntu·面试·typescript
暴躁的菜鸡1 小时前
postgresql16.8二进制包编译
ubuntu·postgresql
^乘风破浪^1 小时前
Ubuntu部署Xingrin(星环)企业级漏洞扫描与资产管理平台
linux·运维·ubuntu
Lueeee.1 小时前
内核模块符号的导出
linux·运维·服务器
C语言魔术师2 小时前
【linux】linux进程概念(四)(环境变量)
linux·运维·服务器
松涛和鸣2 小时前
DAY32 Linux Thread Programming
linux·运维·数据库·算法·list
eggrall2 小时前
《gdb 与 cgdb 深度解析:命令行调试的效率革命》
linux
晨曦夜月2 小时前
头文件与目标文件的关系
linux·开发语言·c++