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

如何通用化实现不同类型对象的布尔属性对比

通用布尔属性比较方法的重构方案

针对你的需求,这里提供两种TypeScript通用实现方案,既能支持任意对象类型,又能自动处理布尔属性的遍历与比较:

方案一:指定属性配对的通用方法(贴近原有逻辑)

这个方案保留了“特定属性配对比较”的核心逻辑,通过泛型和类型约束支持任意对象类型,无需手动创建每个属性配对对象:

// 提取对象中所有布尔类型属性的键
type BooleanPropertyKeys<T> = keyof {
  [K in keyof T as T[K] extends boolean ? K : never]: T[K]
};

function compareBooleanProperties<T, U>(
  left: T,
  right: U,
  propertyPairs: Array<[BooleanPropertyKeys<T>, BooleanPropertyKeys<U>]>
): boolean {
  // 遍历配对数组,检查是否存在任意一组属性同时为true
  return propertyPairs.some(([leftKey, rightKey]) => left[leftKey] && right[rightKey]);
}

使用示例

针对你原有的IFirstType和ISecondType:

const leftObj: IFirstType = {
  propertyOne: true,
  propertyTwo: false,
  propertyThree: false,
  propertyFour: false,
  propertyFive: false
};

const rightObj: ISecondType = {
  firstProperty: true,
  secondProperty: false,
  thirdProperty: false,
  fourthProperty: false,
  fifthProperty: false
};

// 传入属性配对关系,TypeScript会自动校验键的合法性
const result = compareBooleanProperties(leftObj, rightObj, [
  ['propertyOne', 'firstProperty'],
  ['propertyTwo', 'secondProperty'],
  ['propertyThree', 'thirdProperty'],
  // 其他需要配对的属性
]);

方案二:自动遍历所有布尔属性的通用方法

如果你的需求是只要两个对象中存在任意一个布尔属性同时为true就返回true,可以用这个无需指定配对的版本:

type BooleanPropertyKeys<T> = keyof {
  [K in keyof T as T[K] extends boolean ? K : never]: T[K]
};

function compareAllBooleanProperties<T, U>(left: T, right: U): boolean {
  const leftBooleanKeys = Object.keys(left) as BooleanPropertyKeys<T>[];
  const rightBooleanKeys = Object.keys(right) as BooleanPropertyKeys<U>[];

  // 遍历所有布尔属性组合
  for (const leftKey of leftBooleanKeys) {
    if (!left[leftKey]) continue; // left属性为false,跳过后续检查
    for (const rightKey of rightBooleanKeys) {
      if (right[rightKey]) {
        return true; // 找到一组同时为true的属性,直接返回
      }
    }
  }
  return false;
}

使用示例

const result = compareAllBooleanProperties(leftObj, rightObj);

关键特性说明

  • 类型安全:通过BooleanPropertyKeys类型约束,确保只有布尔类型的属性键能被传入,避免非布尔属性的错误调用。
  • 通用性:泛型T和U支持任意对象类型,无需为每种新类型重写方法。
  • 简洁性:无需手动创建PropertyPair对象,直接通过键数组或自动遍历完成逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:35:57