-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
Update.ts
73 lines (68 loc) 路 1.63 KB
/
Update.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import {Key} from '../Any/Key'
import {x} from '../Any/x'
import {Replace} from '../Union/Replace'
import {Depth} from './_Internal'
/**
* @hidden
*/
type UpdateFlat<O extends object, K extends Key, A extends any> = {
[P in keyof O]: P extends K
? Replace<A, x, O[P]>
: O[P]
} & {}
/**
* @hidden
*/
type __UpdateDeep<O, A extends any> = {
[K in keyof O]: Replace<A, x, O[K]> extends infer X
? X extends object
? __UpdateDeep<X, A>
: X
: never
}
/**
* @hidden
*/
type _UpdateDeep<O extends object, K extends Key, A extends any, OU = Update<O, K, x | A>> = {
[K in keyof OU]: __UpdateDeep<OU[K], A>
} & {}
/**
* @hidden
*/
export type UpdateDeep<O extends object, K extends Key, A extends any> =
_UpdateDeep<O, K, A>
/**
* Update in `O` the fields of key `K` with `A`.
* Use the [[x]] placeholder to get the current field type.
* @param O to update
* @param K to chose fields
* @param A to update with
* @returns [[Object]]
* @example
* ```ts
* import {A, O} from 'ts-toolbelt'
*
* type User = {
* info: {
* name: string
* age: number
* payment: {}
* }
* id: number
* }
*
* type test0 = Update<User, 'id' | 'info', A.x | null>
* // {
* // info: {
* // name: string;
* // age: number;
* // payment: {};
* // } | null;
* // id: number | null;
* // }
* ```
*/
export type Update<O extends object, K extends Key, A extends any, depth extends Depth = 'flat'> = {
'flat': UpdateFlat<O, K, A>
'deep': UpdateDeep<O, K, A>
}[depth]