forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
applyDefault.ts
43 lines (37 loc) · 1.21 KB
/
applyDefault.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
34
35
36
37
38
39
40
41
42
43
import { deepMerge, isObjectNotArray } from './deepMerge';
/**
* Pure function - doesn't mutate either parameter!
* Uses the default options and overrides with the options provided by the user
* @param defaultOptions the defaults
* @param userOptions the user opts
* @returns the options with defaults
*/
function applyDefault<TUser extends readonly unknown[], TDefault extends TUser>(
defaultOptions: Readonly<TDefault>,
userOptions: Readonly<TUser> | null,
): TDefault {
// clone defaults
const options = JSON.parse(
JSON.stringify(defaultOptions),
) as AsMutable<TDefault>;
if (userOptions == null) {
return options;
}
// For avoiding the type error
// `This expression is not callable. Type 'unknown' has no call signatures.ts(2349)`
(options as unknown[]).forEach((opt: unknown, i: number) => {
if (userOptions[i] !== undefined) {
const userOpt = userOptions[i];
if (isObjectNotArray(userOpt) && isObjectNotArray(opt)) {
options[i] = deepMerge(opt || {}, userOpt);
} else {
options[i] = userOpt;
}
}
});
return options;
}
type AsMutable<T extends readonly unknown[]> = {
-readonly [TKey in keyof T]: T[TKey];
};
export { applyDefault };