Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/mergeProps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
/**
* Merges multiple props objects into one. Unlike `Object.assign()` or `{ ...a, ...b }`, it skips
* properties whose value is explicitly set to `undefined`.
*
* @example
* ```ts
* const { a, b } = mergeProps(defaults, config, props);
* ```
*/
function mergeProps<A, B>(a: A, b: B): B & A;
function mergeProps<A, B, C>(a: A, b: B, c: C): C & B & A;
Expand All @@ -11,7 +16,13 @@ function mergeProps(...items: any[]) {
if (item) {
for (const key of Object.keys(item)) {
if (item[key] !== undefined) {
ret[key] = item[key];
if (key === 'className') {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

别介,这太黑了。你可以做个配置,支持合并逻辑。

ret[key] = ret[key] ? `${ret[key]} ${item[key]}` : item[key];
} else if (key === 'style') {
ret[key] = { ...ret[key], ...item[key] };
} else {
ret[key] = item[key];
}
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions tests/mergeProps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@ describe('mergeProps', () => {
expect(mergeProps(a, b)).toEqual({ foo: 1, bar: 3, baz: 4 });
});

it('merges className', () => {
const a = { className: 'a' };
const b = { className: 'b' };
expect(mergeProps(a, b)).toEqual({ className: 'a b' });
});

it('merges style', () => {
const a = { style: { color: 'red' } };
const b = { style: { backgroundColor: 'blue' } };
expect(mergeProps(a, b)).toEqual({
style: { color: 'red', backgroundColor: 'blue' },
});
});

it('excludes keys with undefined values', () => {
const a = { foo: 1, bar: undefined };
const b = { bar: 2 };
Expand Down
Loading