Skip to content

feat(mergeProps): add mergeProps function#740

Open
guoyunhe wants to merge 5 commits intoreact-component:masterfrom
guoyunhe:simple-merge-props
Open

feat(mergeProps): add mergeProps function#740
guoyunhe wants to merge 5 commits intoreact-component:masterfrom
guoyunhe:simple-merge-props

Conversation

@guoyunhe
Copy link
Contributor

@guoyunhe guoyunhe commented Mar 17, 2026

Copied from ant-design-mobile https://github.com/ant-design/ant-design-mobile/blob/master/src/utils/with-default-props.tsx

Maybe reused in ant-design

Summary by CodeRabbit

发行说明

  • 新功能
    • 新增 mergeProps 功能:可合并多个对象属性,靠右对象优先,自动忽略值为 undefined 的键,安全处理 null/undefined 输入,支持多参数合并并返回合并结果(浅拷贝行为)。
  • 测试
    • 为 mergeProps 添加了全面单元测试,覆盖冲突解决、undefined 忽略、空输入和多对象合并等场景。

@vercel
Copy link

vercel bot commented Mar 17, 2026

@guoyunhe is attempting to deploy a commit to the React Component Team on Vercel.

A member of the Team first needs to authorize it.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new utility function, mergeProps, designed to streamline the process of combining properties from several objects into one. This function is particularly useful for scenarios where default properties need to be overridden by user-provided ones, ensuring that only defined values are applied and later arguments take precedence. The addition enhances the library's utility belt, making property management more robust and predictable.

Highlights

  • New Utility Function: A new mergeProps utility function has been introduced to facilitate merging properties from multiple objects.
  • Property Merging Logic: The mergeProps function iterates through provided objects, merging their properties into a single result. If a property exists in multiple objects, the value from the later object in the argument list will take precedence, provided it is not undefined.
  • TypeScript Overloads: The function includes TypeScript overloads for up to four arguments, providing type safety and improved developer experience when merging a known number of objects.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/index.ts
    • Exported the newly added mergeProps utility function.
  • src/mergeProps.tsx
    • Added the implementation for the mergeProps function, including TypeScript overloads for type safety.
    • Implemented logic to merge properties from multiple objects, with later objects overriding earlier ones for defined properties.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Mar 17, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 72648070-b800-481d-8740-c509acd28928

📥 Commits

Reviewing files that changed from the base of the PR and between 57cd197 and 534bcef.

📒 Files selected for processing (1)
  • src/mergeProps.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/mergeProps.ts

Walkthrough

添加了新的工具函数 mergeProps(实现及测试)并将其作为命名导出暴露在包的公共 API 中;实现会合并多个 props 对象,跳过值为 undefined 的键,后面的对象优先覆盖前面的属性。

Changes

Cohort / File(s) Summary
核心实现
src/mergeProps.ts
新增 mergeProps 函数实现,提供 2–4 参数的重载签名及可变参数实现;合并时跳过 undefined 值并返回合并结果(默认导出)。
公开导出
src/index.ts
./mergeProps 的默认导出作为命名导出 mergeProps 添加到包的公共导出列表。
单元测试
tests/mergeProps.test.ts
新增全面测试覆盖:右侧覆盖规则、过滤 undefined、跳过 null/undefined 操作数、支持 3+ 对象合并、空参数与单对象返回拷贝、处理空对象等场景。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • zombieJ

庆祝诗

🐰 我在代码田野跑,合并属性不怕烦,
右侧值来当王位,undefined 都请别来,
新测例把路铺好,合并安全又漂亮。 🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题清晰准确地概括了本次变更的主要内容:添加mergeProps函数。标题简洁明了,遵循约定式提交规范(feat前缀),直接反映了拉取请求的核心目标。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a mergeProps utility function, which is useful for merging multiple props objects while filtering out undefined values. The implementation is functional, but I have a couple of suggestions to improve code clarity and maintainability. Specifically, I've recommended refactoring the function body for better readability and renaming the file to use a .ts extension since it doesn't contain JSX.

@codecov
Copy link

codecov bot commented Mar 17, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.31%. Comparing base (2a5333e) to head (534bcef).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #740      +/-   ##
==========================================
+ Coverage   86.20%   86.31%   +0.10%     
==========================================
  Files          38       39       +1     
  Lines        1044     1052       +8     
  Branches      385      372      -13     
==========================================
+ Hits          900      908       +8     
  Misses        142      142              
  Partials        2        2              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/mergeProps.tsx (2)

4-16: composeProps 的行为差异可能导致事件处理器被意外覆盖

根据 src/composeProps.ts 的实现,composeProps 会将函数类型的属性进行链式组合(两个回调都会被调用)。而 mergeProps 使用简单覆盖语义 (ret[key] = item[key]),后传入的函数会完全替换前者。

如果开发者在合并 React 组件 props 时误用 mergeProps 来合并事件处理器(如 onClick),可能会导致原有的处理器被静默丢弃。

建议在函数上方添加 JSDoc 文档,明确说明:

  1. 这是浅合并(shallow merge)
  2. 后者覆盖前者
  3. 函数属性不会被组合,若需组合回调应使用 composeProps
📝 建议添加文档注释
+/**
+ * Shallow merge multiple objects into one. Later values override earlier ones.
+ * Properties with `undefined` value are skipped.
+ *
+ * Note: Unlike `composeProps`, this function does NOT compose callback functions.
+ * If you need to chain event handlers, use `composeProps` instead.
+ */
 function mergeProps<A, B>(a: A, b: B): B & A;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mergeProps.tsx` around lines 4 - 16, The mergeProps implementation
performs a shallow merge that overwrites earlier values with later ones (it does
not compose functions), so add a JSDoc comment above the mergeProps function
stating that: (1) this is a shallow merge, (2) later items override earlier
items, and (3) function-valued props (e.g., event handlers like onClick) will be
replaced rather than composed and that callers should use composeProps if they
need to chain callbacks; reference the mergeProps and composeProps names in the
comment to guide future maintainers.

1-3: 类型重载仅支持最多 4 个参数

当前仅提供了 2-4 个参数的重载签名。若调用时传入 5 个或更多参数,返回类型将退化为 any,丢失类型安全。

建议添加更多重载,或至少添加一个 fallback 签名以保持基本的类型提示:

♻️ 建议的修改
 function mergeProps<A, B>(a: A, b: B): B & A;
 function mergeProps<A, B, C>(a: A, b: B, c: C): C & B & A;
 function mergeProps<A, B, C, D>(a: A, b: B, c: C, d: D): D & C & B & A;
+function mergeProps<A, B, C, D, E>(a: A, b: B, c: C, d: D, e: E): E & D & C & B & A;
+function mergeProps<T extends object>(...items: T[]): T;
 function mergeProps(...items: any[]) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mergeProps.tsx` around lines 1 - 3, The overloads for mergeProps
currently only cover 2–4 args causing calls with 5+ args to lose types; update
mergeProps to handle arbitrarily many arguments by adding either extra explicit
overloads (e.g., up to 6–8) or, preferably, a variadic fallback signature using
a tuple generic and an intersection helper type. Concretely, keep the existing
specific overloads, then add a final signature like a variadic rest: function
mergeProps<T extends any[]>(...args: T): /* intersection of all T[number] */ and
implement a small type helper (commonly named UnionToIntersection or
MergeTupleToIntersection) to transform T[number] into the intersection result;
ensure the runtime mergeProps implementation still accepts rest args and returns
the merged object.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/mergeProps.tsx`:
- Around line 4-16: The mergeProps implementation performs a shallow merge that
overwrites earlier values with later ones (it does not compose functions), so
add a JSDoc comment above the mergeProps function stating that: (1) this is a
shallow merge, (2) later items override earlier items, and (3) function-valued
props (e.g., event handlers like onClick) will be replaced rather than composed
and that callers should use composeProps if they need to chain callbacks;
reference the mergeProps and composeProps names in the comment to guide future
maintainers.
- Around line 1-3: The overloads for mergeProps currently only cover 2–4 args
causing calls with 5+ args to lose types; update mergeProps to handle
arbitrarily many arguments by adding either extra explicit overloads (e.g., up
to 6–8) or, preferably, a variadic fallback signature using a tuple generic and
an intersection helper type. Concretely, keep the existing specific overloads,
then add a final signature like a variadic rest: function mergeProps<T extends
any[]>(...args: T): /* intersection of all T[number] */ and implement a small
type helper (commonly named UnionToIntersection or MergeTupleToIntersection) to
transform T[number] into the intersection result; ensure the runtime mergeProps
implementation still accepts rest args and returns the merged object.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1516228e-3796-492c-bfed-16823fe807df

📥 Commits

Reviewing files that changed from the base of the PR and between 2a5333e and 0b13959.

📒 Files selected for processing (2)
  • src/index.ts
  • src/mergeProps.tsx

guoyunhe and others added 3 commits March 17, 2026 14:50
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/mergeProps.ts (1)

1-3: 类型重载未覆盖超过 4 个参数的情况。

当前仅提供了 2-4 个参数的类型重载,但运行时实现支持任意数量的参数。建议添加一个通用的重载签名以支持更多参数的场景。

♻️ 建议添加通用重载签名
 function mergeProps<A, B>(a: A, b: B): B & A;
 function mergeProps<A, B, C>(a: A, b: B, c: C): C & B & A;
 function mergeProps<A, B, C, D>(a: A, b: B, c: C, d: D): D & C & B & A;
+function mergeProps<T extends object[]>(...items: T): object;
 function mergeProps(...items: any[]) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/mergeProps.ts` around lines 1 - 3, The overloads for mergeProps
(functions mergeProps<A,B>, mergeProps<A,B,C>, mergeProps<A,B,C,D>) don't cover
calls with more than four arguments even though the implementation accepts any
number; add a general overload signature like function mergeProps<T extends
object[]>(...objs: T): UnionToIntersection<T[number]> (or a generic
rest-parameter overload returning an intersection of all input types) so
TypeScript understands arbitrary-arity usage of mergeProps while keeping
existing specific overloads for better inference.
tests/mergeProps.test.ts (1)

41-47: 建议验证返回的是浅拷贝(不同引用)。

当前测试只验证了返回值与原对象相等,但未验证返回的是一个新对象(不同引用)。建议增加引用不相等的断言,以确保函数确实返回了浅拷贝。

♻️ 建议增加引用检查
   it('returns copy of single object', () => {
     const a = { foo: 1, bar: 2 };
-    expect((mergeProps as (...items: any[]) => any)(a)).toEqual({
+    const result = (mergeProps as (...items: any[]) => any)(a);
+    expect(result).toEqual({
       foo: 1,
       bar: 2,
     });
+    expect(result).not.toBe(a);
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/mergeProps.test.ts` around lines 41 - 47, The test currently only
checks deep equality; update the spec for mergeProps so it also asserts the
returned object is a different reference than the input (i.e., not the same
object) to verify a shallow copy is returned—call mergeProps(a) into a result
variable and add an assertion like expect(result).not.toBe(a) (and optionally
verify nested object references remain the same if you want to confirm "shallow"
behavior).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/mergeProps.ts`:
- Around line 1-3: The overloads for mergeProps (functions mergeProps<A,B>,
mergeProps<A,B,C>, mergeProps<A,B,C,D>) don't cover calls with more than four
arguments even though the implementation accepts any number; add a general
overload signature like function mergeProps<T extends object[]>(...objs: T):
UnionToIntersection<T[number]> (or a generic rest-parameter overload returning
an intersection of all input types) so TypeScript understands arbitrary-arity
usage of mergeProps while keeping existing specific overloads for better
inference.

In `@tests/mergeProps.test.ts`:
- Around line 41-47: The test currently only checks deep equality; update the
spec for mergeProps so it also asserts the returned object is a different
reference than the input (i.e., not the same object) to verify a shallow copy is
returned—call mergeProps(a) into a result variable and add an assertion like
expect(result).not.toBe(a) (and optionally verify nested object references
remain the same if you want to confirm "shallow" behavior).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c8a6a023-f885-45d7-8d6b-79b6a0ff823b

📥 Commits

Reviewing files that changed from the base of the PR and between 0b13959 and 57cd197.

📒 Files selected for processing (2)
  • src/mergeProps.ts
  • tests/mergeProps.test.ts

function mergeProps<A, B>(a: A, b: B): B & A;
function mergeProps<A, B, C>(a: A, b: B, c: C): C & B & A;
function mergeProps<A, B, C, D>(a: A, b: B, c: C, d: D): D & C & B & A;
function mergeProps(...items: any[]) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

多个 useMergeProps?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

目前感觉不是很必要,因为每次 render 的 props 实例总是变化的,memo 不住呢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants