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

相关推荐
jugt1 小时前
CentOS 7.9安装Nginx1.24.0时报 checking for LuaJIT 2.x ... not found
linux·运维·centos
多多*2 小时前
LUA+Reids实现库存秒杀预扣减 记录流水 以及自己的思考
linux·开发语言·redis·python·bootstrap·lua
何双新3 小时前
第21讲、Odoo 18 配置机制详解
linux·python·开源
21号 13 小时前
9.进程间通信
linux·运维·服务器
藥瓿亭8 小时前
K8S认证|CKS题库+答案| 3. 默认网络策略
运维·ubuntu·docker·云原生·容器·kubernetes·cks
Gaoithe8 小时前
ubuntu 端口复用
linux·运维·ubuntu
dancing9999 小时前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
德先生&赛先生9 小时前
Linux编程:1、文件编程
linux
程序猿小D9 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
多多*10 小时前
微服务网关SpringCloudGateway+SaToken鉴权
linux·开发语言·redis·python·sql·log4j·bootstrap