forked from sindresorhus/type-fest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spread.d.ts
85 lines (67 loc) · 1.77 KB
/
spread.d.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
74
75
76
77
78
79
80
81
82
83
84
85
import type {Except} from './except';
import type {RequiredKeysOf} from './required-keys-of';
import type {Simplify} from './simplify';
type SpreadObject<FirstType extends object, SecondType extends object> = {
[Key in keyof FirstType]: Key extends keyof SecondType
? FirstType[Key] | Required<SecondType>[Key]
: FirstType[Key];
} & Pick<
SecondType,
RequiredKeysOf<SecondType> | Exclude<keyof SecondType, keyof FirstType>
>;
type TupleOrArray = readonly [...unknown[]];
type SpreadTupleOrArray<
FirstType extends TupleOrArray,
SecondType extends TupleOrArray,
> = Array<FirstType[number] | SecondType[number]>;
type Spreadable = object | TupleOrArray;
/**
Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.
@example
```
import type {Spread} from 'type-fest';
type Foo = {
a: number;
b?: string;
};
type Bar = {
b?: number;
c: boolean;
};
const foo = {a: 1, b: '2'};
const bar = {c: false};
const fooBar = {...foo, ...bar};
type FooBar = Spread<Foo, Bar>;
// type FooBar = {
// a: number;
// b?: string | number | undefined;
// c: boolean;
// }
const baz = (argument: FooBar) => {
// Do something
}
baz(fooBar);
```
@example
```
import type {Spread} from 'type-fest';
const foo = [1, 2, 3];
const bar = ['4', '5', '6'];
const fooBar = [...foo, ...bar];
type FooBar = Spread<typeof foo, typeof bar>;
// FooBar = (string | number)[]
const baz = (argument: FooBar) => {
// Do something
};
baz(fooBar);
```
@category Object
*/
export type Spread<
FirstType extends Spreadable,
SecondType extends Spreadable,
> = FirstType extends TupleOrArray
? SecondType extends TupleOrArray
? SpreadTupleOrArray<FirstType, SecondType>
: Simplify<SpreadObject<FirstType, SecondType>>
: Simplify<SpreadObject<FirstType, SecondType>>;