From 24b9aa90e4912f29cb80c625720e1ed0cf80d8b3 Mon Sep 17 00:00:00 2001 From: Rebecca Stevens Date: Tue, 10 Nov 2020 18:10:23 +1300 Subject: [PATCH] fix: handle user functions in typings --- types/index.d.ts | 91 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 70 insertions(+), 21 deletions(-) diff --git a/types/index.d.ts b/types/index.d.ts index 34aa7e2..27f2500 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -46,34 +46,63 @@ type DeepMergeObjectProps< Options extends deepmerge.Options > = FlatternAlias< { - -readonly [K in keyof T1]: Options["customMerge"] extends undefined - ? DeepMerge, ValueOfKey, Options> - : ReturnType> extends undefined - ? DeepMerge, ValueOfKey, Options> - : ReturnType< - NonNullable>> - >; + -readonly [K in keyof T1]: DeepMergeProps< + ValueOfKey, + ValueOfKey, + Options + >; } & { - -readonly [K in keyof T2]: Options["customMerge"] extends undefined - ? DeepMerge, ValueOfKey, Options> - : ReturnType> extends undefined - ? DeepMerge, ValueOfKey, Options> - : ReturnType< - NonNullable>> - >; + -readonly [K in keyof T2]: DeepMergeProps< + ValueOfKey, + ValueOfKey, + Options + >; } >; +type DeepMergeProps = GetOption< + Options, + "isMergeableObject" +> extends undefined + ? GetOption extends undefined + ? DeepMerge + : DeepMergePropsCustom + : MergeMaybeLeafs; + +type DeepMergePropsCustom< + T1, + T2, + Options extends deepmerge.Options +> = ReturnType>> extends undefined + ? DeepMerge + : undefined extends ReturnType>> + ? IsArray extends true + ? IsArray extends true + ? DeepMergeArrays + : MergeLeafs + : IsArray extends true + ? MergeLeafs + : + | DeepMerge + | ReturnType< + NonNullable< + ReturnType>> + > + > + : ReturnType< + NonNullable>>> + >; + type DeepMergeArrays< T1, T2, Options extends deepmerge.Options > = T1 extends readonly [...infer E1] ? T2 extends readonly [...infer E2] - ? Options["arrayMerge"] extends undefined + ? GetOption extends undefined ? [...E1, ...E2] - : ReturnType> + : ReturnType>> : never : never; @@ -85,11 +114,24 @@ type MergeLeafs = Is extends true ? T1 : T2; -type FlatternAlias = T extends any - ? { - [K in keyof T]: T[K]; - } - : never; +type MergeMaybeLeafs = Is< + T2, + never +> extends true + ? T1 + : Is extends true + ? T2 + : Is extends true + ? T1 + : Is extends true + ? T2 + : Is extends false + ? DeepMerge + : Is extends false + ? DeepMerge + : unknown; + +type FlatternAlias = {} & { [P in keyof T]: T[P] }; type ValueOfKey = K extends keyof T ? T[K] : never; @@ -103,6 +145,8 @@ type IsObject = Is> extends true ? false : IsObjectOrArray; +type IsArray = Is>; + type ShouldMergeObjects = IsObject extends true ? IsObject : false; @@ -133,6 +177,11 @@ type DefaultOptions = { isMergeableObject: undefined; }; +type GetOption< + O extends deepmerge.Options, + K extends keyof deepmerge.Options +> = undefined extends O[K] ? DefaultOptions[K] : O[K]; + /** * Deeply merge two objects. *