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

如何实现TypeScript泛型MagicGenerator生成指定键的全布尔组合类型?

实现TypeScript泛型MagicGenerator生成所有布尔组合类型

你需要的是生成Keys的所有布尔组合,覆盖全true、部分true+其余可选false、全可选false三种场景,原实现仅覆盖了首尾两种,缺少部分true的组合。以下是完整的解决方案:

核心思路

分三部分覆盖所有场景:

  • 全Keys为true:生成所有Key为必选true的对象,合并Props;
  • 部分Keys为true:遍历每个Key,生成该Key为必选true、其余Key为可选false的对象,合并Props;
  • 全Keys为可选false:生成所有Key为可选false的对象,同时将Props的所有属性设为可选never。

完整实现代码

// 工具类型:生成单个Key为true、其余为可选false的所有组合
type PartialTrue<Keys extends string> = {
  [K in Keys]: { [_ in K]: true } & Partial<Record<Exclude<Keys, K>, false>>
}[Keys];

type MagicGenerator<Keys extends string, Props extends object> =
  // 场景1:所有Keys均为true,合并Props
  ({ [K in Keys]: true } & Props)
  // 场景2:单个Keys为true、其余可选false,合并Props
  | (PartialTrue<Keys> & Props)
  // 场景3:所有Keys均为可选false,Props属性设为可选never
  | ({ [K in Keys]?: false } & { [P in keyof Props]?: never });

测试用例

// 定义测试用的Keys和Props
type FeatureKeys = 'withWishlist' | 'withAddToCart';
type ComponentProps = { pickerProp: any };

// 生成完整的组合类型
type FullResult = MagicGenerator<FeatureKeys, ComponentProps>;

生成的FullResult会展开为:

type FullResult = {
    withWishlist: true;
    withAddToCart: true;
    pickerProp: any;
} | {
    withWishlist: true;
    withAddToCart?: false | undefined;
    pickerProp: any;
} | {
    withAddToCart: true;
    withWishlist?: false | undefined;
    pickerProp: any;
} | {
    withWishlist?: false | undefined;
    withAddToCart?: false | undefined;
    pickerProp?: undefined;
}

原实现问题说明

原代码仅处理了全true和全可选false两种极端情况,没有遍历每个Key生成部分true的组合,因此缺少中间的场景。通过新增PartialTrue工具类型遍历每个Key,就能覆盖所有部分true的组合。

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:35:14