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

如何在TypeScript中实现两个类型的cross-product(笛卡尔积)

你可以直接使用 TypeScript 内置的模板字面量类型特性实现自动生成,无需手动枚举所有组合:

type color = "red" | "green";
type shade = "100" | "200" | "300";

// 自动生成两个联合类型的笛卡尔积拼接结果
type ColorShade = `${color}.${shade}`

此时 ColorShade 的取值就和你手动写的完全一致,会自动包含所有合法的拼接组合。后续如果 color 或 shade 新增枚举值,ColorShade 会自动同步更新,不需要手动修改。

注意:该特性需要 TypeScript 4.1 及以上版本支持

如果需要复用这个逻辑,你还可以封装成通用的工具类型:

type JoinCrossProduct<
  T extends string | number | bigint | boolean | null | undefined,
  U extends string | number | bigint | boolean | null | undefined,
  Separator extends string = "."
> = `${T}${Separator}${U}`;

// 使用示例
type ColorShade = JoinCrossProduct<color, shade>;
// 也可以自定义分隔符,比如用下划线
type ColorShadeUnderline = JoinCrossProduct<color, shade, "_">;

内容的提问来源于stack exchange,提问作者potatoxchip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:45:03