You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从类构造函数数组生成对应的交叉类型?

将数组中类构造函数的类型转换为交叉类型

问题描述

假设我有一个包含类构造函数的数组,例如:

const arr = [A, B, C, D]

如何将该数组的类型映射为这些项的交叉类型,即:

type IntersectedTypes = A & B & C & D

并且该方法要适用于不同的数组。我尝试使用type IntersectedTypes = (typeof arr)[number],但得到的只是联合类型typeof A | typeof B | typeof C | typeof D。

解决方案

要实现将数组元素的类型转换为交叉类型,需要借助TypeScript的条件类型递归和可变元组类型来处理,具体步骤如下:

1. 定义元组转交叉类型的工具类型

先写一个通用工具类型,递归遍历元组的每一项并将它们交叉:

type TupleToIntersection<T extends any[]> = 
  T extends [infer First, ...infer Rest] 
    ? First & TupleToIntersection<Rest> 
    : unknown;

空元组时返回unknown,作为交叉操作的中性值,不会影响最终的交叉结果。

2. 保留数组的元组字面量类型

TypeScript默认会把[A, B, C, D]推断为联合类型数组,需要用as const断言让TypeScript保留数组的具体元组结构:

const arr = [A, B, C, D] as const;

3. 转换为交叉类型

现在直接用工具类型处理数组的类型即可:

type IntersectedTypes = TupleToIntersection<typeof arr>;

此时IntersectedTypes的类型就是typeof A & typeof B & typeof C & typeof D,完全符合需求。

完整示例

class A { a: string }
class B { b: number }
class C { c: boolean }
class D { d: symbol }

const arr = [A, B, C, D] as const;

type TupleToIntersection<T extends any[]> = 
  T extends [infer First, ...infer Rest] 
    ? First & TupleToIntersection<Rest> 
    : unknown;

type IntersectedTypes = TupleToIntersection<typeof arr>;
// 最终类型:typeof A & typeof B & typeof C & typeof D

适配任意数组

这个方案适用于任意长度的类构造函数数组,只要对数组添加as const断言保留元组结构,就能通过TupleToIntersection工具类型转换为对应的交叉类型。


内容的提问来源于stack exchange,提问作者Lucas Vinícius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:29:53