generated from garronej/ts-ci
-
Notifications
You must be signed in to change notification settings - Fork 6
/
withDefaults.ts
33 lines (32 loc) 路 1.18 KB
/
withDefaults.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-explicit-any */
import "../tools/Object.fromEntries.ts";
/**
* Like Function.prototype.bind() but for a function that
* receives their parameters wrapped in an object.
* See documentation for more details:
* https://docs.tsafe.dev/withdefaults
*/
export function withDefaults<Params extends Record<string, unknown>, DefaultKey extends keyof Params, R>(
f: (params: Params) => R,
defaultParams: keyof Params extends never
? Record<string, never>
: { [Key in DefaultKey]: Params[Key] },
): (
params: { [Key in keyof Omit<Params, DefaultKey>]: Params[Key] } & {
defaultsOverwrite?: { [Key in DefaultKey]?: [Params[Key]] };
},
) => R {
return params => {
const { defaultsOverwrite = {}, ...actualParams } = params;
return f({
...defaultParams,
...actualParams,
...Object.fromEntries(
Object.entries(defaultsOverwrite)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, (value as any)[0]]),
),
} as any);
};
}