如何在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
相关产品推荐
相关产品推荐

