Skip to content

Commit fcdf14b

Browse files
committed
Fix deep mapper parameter TypeScript types
Fixes #22
1 parent 025aa63 commit fcdf14b

2 files changed

Lines changed: 25 additions & 10 deletions

File tree

index.d.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,24 @@ export type Mapper<
2929
mapperOptions?: MapperOptions,
3030
] | typeof mapObjectSkip;
3131

32+
/**
33+
Mapper used when `{deep: true}` is enabled.
34+
35+
In deep mode we may visit nested objects with keys and values unrelated to the top-level object, so we intentionally widen the key and value types.
36+
*/
37+
export type DeepMapper<
38+
MappedObjectKeyType extends string,
39+
MappedObjectValueType,
40+
> = (
41+
sourceKey: string,
42+
sourceValue: any,
43+
source: any
44+
) => [
45+
targetKey: MappedObjectKeyType,
46+
targetValue: MappedObjectValueType,
47+
mapperOptions?: MapperOptions,
48+
] | typeof mapObjectSkip;
49+
3250
export interface Options {
3351
/**
3452
Recurse nested objects and objects in arrays.
@@ -98,11 +116,7 @@ export default function mapObject<
98116
MappedObjectValueType,
99117
>(
100118
source: SourceObjectType,
101-
mapper: Mapper<
102-
SourceObjectType,
103-
MappedObjectKeyType,
104-
MappedObjectValueType
105-
>,
119+
mapper: DeepMapper<MappedObjectKeyType, MappedObjectValueType>,
106120
options: DeepOptions & TargetOptions<TargetObjectType>
107121
): TargetObjectType & Record<string, unknown>;
108122
export default function mapObject<
@@ -111,11 +125,7 @@ export default function mapObject<
111125
MappedObjectValueType,
112126
>(
113127
source: SourceObjectType,
114-
mapper: Mapper<
115-
SourceObjectType,
116-
MappedObjectKeyType,
117-
MappedObjectValueType
118-
>,
128+
mapper: DeepMapper<MappedObjectKeyType, MappedObjectValueType>,
119129
options: DeepOptions
120130
): Record<string, unknown>;
121131
export default function mapObject<

index.test-d.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ const object2 = mapObject({foo: 'bar'}, (key, value) => [value, key], {
2626
deep: true,
2727
});
2828
expectType<Record<string, unknown>>(object2);
29+
// Deep mapper parameters should be widened
30+
mapObject({fooUpper: true, bAr: {bAz: true}}, (key, value) => {
31+
expectType<string>(key);
32+
return [String(key), value];
33+
}, {deep: true});
2934
const object3 = mapObject({foo: 'bar'}, (key, value) => [value, key], {
3035
deep: true,
3136
target: {bar: 'baz' as const},

0 commit comments

Comments
 (0)