-
-
Notifications
You must be signed in to change notification settings - Fork 230
/
mapped-types.ts
661 lines (621 loc) · 18.2 KB
/
mapped-types.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import { Primitive } from './aliases-and-guards';
/**
* Credits to all the people who given inspiration and shared some very useful code snippets
* in the following github issue: https://github.com/Microsoft/TypeScript/issues/12215
*/
/**
* SetIntersection (same as Extract)
* @desc Set intersection of given union types `A` and `B`
* @example
* // Expect: "2" | "3"
* SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>;
*
* // Expect: () => void
* SetIntersection<string | number | (() => void), Function>;
*/
export type SetIntersection<A, B> = A extends B ? A : never;
/**
* SetDifference (same as Exclude)
* @desc Set difference of given union types `A` and `B`
* @example
* // Expect: "1"
* SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
*
* // Expect: string | number
* SetDifference<string | number | (() => void), Function>;
*/
export type SetDifference<A, B> = A extends B ? never : A;
/**
* SetComplement
* @desc Set complement of given union types `A` and (it's subset) `A1`
* @example
* // Expect: "1"
* SetComplement<'1' | '2' | '3', '2' | '3'>;
*/
export type SetComplement<A, A1 extends A> = SetDifference<A, A1>;
/**
* SymmetricDifference
* @desc Set difference of union and intersection of given union types `A` and `B`
* @example
* // Expect: "1" | "4"
* SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>;
*/
export type SymmetricDifference<A, B> = SetDifference<A | B, A & B>;
/**
* NonUndefined
* @desc Exclude undefined from set `A`
* @example
* // Expect: "string | null"
* SymmetricDifference<string | null | undefined>;
*/
export type NonUndefined<A> = A extends undefined ? never : A;
/**
* NonNullable
* @desc Exclude undefined and null from set `A`
* @example
* // Expect: "string"
* SymmetricDifference<string | null | undefined>;
*/
// type NonNullable - built-in
/**
* FunctionKeys
* @desc Get union type of keys that are functions in object type `T`
* @example
* type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
*
* // Expect: "setName | someFn"
* type Keys = FunctionKeys<MixedProps>;
*/
export type FunctionKeys<T extends object> = {
[K in keyof T]-?: NonUndefined<T[K]> extends Function ? K : never;
}[keyof T];
/**
* NonFunctionKeys
* @desc Get union type of keys that are non-functions in object type `T`
* @example
* type MixedProps = {name: string; setName: (name: string) => void; someKeys?: string; someFn?: (...args: any) => any;};
*
* // Expect: "name | someKey"
* type Keys = NonFunctionKeys<MixedProps>;
*/
export type NonFunctionKeys<T extends object> = {
[K in keyof T]-?: NonUndefined<T[K]> extends Function ? never : K;
}[keyof T];
/**
* MutableKeys
* @desc Get union type of keys that are mutable in object type `T`
* Credit: Matt McCutchen
* https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript
* @example
* type Props = { readonly foo: string; bar: number };
*
* // Expect: "bar"
* type Keys = MutableKeys<Props>;
*/
export type MutableKeys<T extends object> = {
[P in keyof T]-?: IfEquals<
{ [Q in P]: T[P] },
{ -readonly [Q in P]: T[P] },
P
>;
}[keyof T];
export type WritableKeys<T extends object> = MutableKeys<T>;
/**
* ReadonlyKeys
* @desc Get union type of keys that are readonly in object type `T`
* Credit: Matt McCutchen
* https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript
* @example
* type Props = { readonly foo: string; bar: number };
*
* // Expect: "foo"
* type Keys = ReadonlyKeys<Props>;
*/
export type ReadonlyKeys<T extends object> = {
[P in keyof T]-?: IfEquals<
{ [Q in P]: T[P] },
{ -readonly [Q in P]: T[P] },
never,
P
>;
}[keyof T];
type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <
T
>() => T extends Y ? 1 : 2
? A
: B;
/**
* RequiredKeys
* @desc Get union type of keys that are required in object type `T`
* @see https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
*
* // Expect: "req" | "reqUndef"
* type Keys = RequiredKeys<Props>;
*/
export type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
/**
* OptionalKeys
* @desc Get union type of keys that are optional in object type `T`
* @see https://stackoverflow.com/questions/52984808/is-there-a-way-to-get-all-required-properties-of-a-typescript-object
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };
*
* // Expect: "opt" | "optUndef"
* type Keys = OptionalKeys<Props>;
*/
export type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
/**
* UnionKeys
* @desc Get keys of all objects in the union type `U`
* Credit: filipomar
* @see https://github.com/piotrwitek/utility-types/issues/192
* @example
* // Expect: 'name' | 'age' | 'visible'
* UnionKeys<{ name: string; age: string } | { age: number } | { visible: boolean }>
*/
export type UnionKeys<U> = keyof UnionToIntersection<Partial<U>>;
/**
* Pick (complements Omit)
* @desc From `T` pick a set of properties by key `K`
* @example
* type Props = { name: string; age: number; visible: boolean };
*
* // Expect: { age: number; }
* type Props = Pick<Props, 'age'>;
*/
namespace Pick {}
/**
* PickByValue
* @desc From `T` pick a set of properties by value matching `ValueType`.
* Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c)
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; };
*
* // Expect: { req: number }
* type Props = PickByValue<Props, number>;
* // Expect: { req: number; reqUndef: number | undefined; }
* type Props = PickByValue<Props, number | undefined>;
*/
export type PickByValue<T, ValueType> = Pick<
T,
{ [Key in keyof T]-?: T[Key] extends ValueType ? Key : never }[keyof T]
>;
/**
* PickByValueExact
* @desc From `T` pick a set of properties by value matching exact `ValueType`.
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; };
*
* // Expect: { req: number }
* type Props = PickByValueExact<Props, number>;
* // Expect: { reqUndef: number | undefined; }
* type Props = PickByValueExact<Props, number | undefined>;
*/
export type PickByValueExact<T, ValueType> = Pick<
T,
{
[Key in keyof T]-?: [ValueType] extends [T[Key]]
? [T[Key]] extends [ValueType]
? Key
: never
: never;
}[keyof T]
>;
/**
* Omit (complements Pick)
* @desc From `T` remove a set of properties by key `K`
* @example
* type Props = { name: string; age: number; visible: boolean };
*
* // Expect: { name: string; visible: boolean; }
* type Props = Omit<Props, 'age'>;
*/
export type Omit<T, K extends keyof any> = Pick<T, SetDifference<keyof T, K>>;
/**
* OmitByValue
* @desc From `T` remove a set of properties by value matching `ValueType`.
* Credit: [Piotr Lewandowski](https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c)
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; };
*
* // Expect: { reqUndef: number | undefined; opt?: string; }
* type Props = OmitByValue<Props, number>;
* // Expect: { opt?: string; }
* type Props = OmitByValue<Props, number | undefined>;
*/
export type OmitByValue<T, ValueType> = Pick<
T,
{ [Key in keyof T]-?: T[Key] extends ValueType ? never : Key }[keyof T]
>;
/**
* OmitByValueExact
* @desc From `T` remove a set of properties by value matching exact `ValueType`.
* @example
* type Props = { req: number; reqUndef: number | undefined; opt?: string; };
*
* // Expect: { reqUndef: number | undefined; opt?: string; }
* type Props = OmitByValueExact<Props, number>;
* // Expect: { req: number; opt?: string }
* type Props = OmitByValueExact<Props, number | undefined>;
*/
export type OmitByValueExact<T, ValueType> = Pick<
T,
{
[Key in keyof T]-?: [ValueType] extends [T[Key]]
? [T[Key]] extends [ValueType]
? never
: Key
: Key;
}[keyof T]
>;
/**
* Intersection
* @desc From `T` pick properties that exist in `U`
* @example
* type Props = { name: string; age: number; visible: boolean };
* type DefaultProps = { age: number };
*
* // Expect: { age: number; }
* type DuplicateProps = Intersection<Props, DefaultProps>;
*/
export type Intersection<T extends object, U extends object> = Pick<
T,
Extract<keyof T, keyof U> & Extract<keyof U, keyof T>
>;
/**
* Diff
* @desc From `T` remove properties that exist in `U`
* @example
* type Props = { name: string; age: number; visible: boolean };
* type DefaultProps = { age: number };
*
* // Expect: { name: string; visible: boolean; }
* type DiffProps = Diff<Props, DefaultProps>;
*/
export type Diff<T extends object, U extends object> = Pick<
T,
SetDifference<keyof T, keyof U>
>;
/**
* Subtract
* @desc From `T` remove properties that exist in `T1` (`T1` has a subset of the properties of `T`)
* @example
* type Props = { name: string; age: number; visible: boolean };
* type DefaultProps = { age: number };
*
* // Expect: { name: string; visible: boolean; }
* type RestProps = Subtract<Props, DefaultProps>;
*/
export type Subtract<T extends T1, T1 extends object> = Pick<
T,
SetComplement<keyof T, keyof T1>
>;
/**
* Overwrite
* @desc From `U` overwrite properties to `T`
* @example
* type Props = { name: string; age: number; visible: boolean };
* type NewProps = { age: string; other: string };
*
* // Expect: { name: string; age: string; visible: boolean; }
* type ReplacedProps = Overwrite<Props, NewProps>;
*/
export type Overwrite<
T extends object,
U extends object,
I = Diff<T, U> & Intersection<U, T>
> = Pick<I, keyof I>;
/**
* Assign
* @desc From `U` assign properties to `T` (just like object assign)
* @example
* type Props = { name: string; age: number; visible: boolean };
* type NewProps = { age: string; other: string };
*
* // Expect: { name: string; age: number; visible: boolean; other: string; }
* type ExtendedProps = Assign<Props, NewProps>;
*/
export type Assign<
T extends object,
U extends object,
I = Diff<T, U> & Intersection<U, T> & Diff<U, T>
> = Pick<I, keyof I>;
/**
* Exact
* @desc Create branded object type for exact type matching
*/
export type Exact<A extends object> = A & { __brand: keyof A };
/**
* Unionize
* @desc Disjoin object to form union of objects, each with single property
* @example
* type Props = { name: string; age: number; visible: boolean };
*
* // Expect: { name: string; } | { age: number; } | { visible: boolean; }
* type UnionizedType = Unionize<Props>;
*/
export type Unionize<T extends object> = {
[P in keyof T]: { [Q in P]: T[P] };
}[keyof T];
/**
* PromiseType
* @desc Obtain Promise resolve type
* @example
* // Expect: string;
* type Response = PromiseType<Promise<string>>;
*/
export type PromiseType<T extends Promise<any>> = T extends Promise<infer U>
? U
: never;
// TODO: inline _DeepReadonlyArray with infer in DeepReadonly, same for all other deep types
/**
* DeepReadonly
* @desc Readonly that works for deeply nested structure
* @example
* // Expect: {
* // readonly first: {
* // readonly second: {
* // readonly name: string;
* // };
* // };
* // }
* type NestedProps = {
* first: {
* second: {
* name: string;
* };
* };
* };
* type ReadonlyNestedProps = DeepReadonly<NestedProps>;
*/
export type DeepReadonly<T> = T extends ((...args: any[]) => any) | Primitive
? T
: T extends _DeepReadonlyArray<infer U>
? _DeepReadonlyArray<U>
: T extends _DeepReadonlyObject<infer V>
? _DeepReadonlyObject<V>
: T;
/** @private */
// tslint:disable-next-line:class-name
export interface _DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {}
/** @private */
export type _DeepReadonlyObject<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
/**
* DeepRequired
* @desc Required that works for deeply nested structure
* @example
* // Expect: {
* // first: {
* // second: {
* // name: string;
* // };
* // };
* // }
* type NestedProps = {
* first?: {
* second?: {
* name?: string;
* };
* };
* };
* type RequiredNestedProps = DeepRequired<NestedProps>;
*/
export type DeepRequired<T> = T extends (...args: any[]) => any
? T
: T extends any[]
? _DeepRequiredArray<T[number]>
: T extends object
? _DeepRequiredObject<T>
: T;
/** @private */
// tslint:disable-next-line:class-name
export interface _DeepRequiredArray<T>
extends Array<DeepRequired<NonUndefined<T>>> {}
/** @private */
export type _DeepRequiredObject<T> = {
[P in keyof T]-?: DeepRequired<NonUndefined<T[P]>>;
};
/**
* DeepNonNullable
* @desc NonNullable that works for deeply nested structure
* @example
* // Expect: {
* // first: {
* // second: {
* // name: string;
* // };
* // };
* // }
* type NestedProps = {
* first?: null | {
* second?: null | {
* name?: string | null |
* undefined;
* };
* };
* };
* type RequiredNestedProps = DeepNonNullable<NestedProps>;
*/
export type DeepNonNullable<T> = T extends (...args: any[]) => any
? T
: T extends any[]
? _DeepNonNullableArray<T[number]>
: T extends object
? _DeepNonNullableObject<T>
: T;
/** @private */
// tslint:disable-next-line:class-name
export interface _DeepNonNullableArray<T>
extends Array<DeepNonNullable<NonNullable<T>>> {}
/** @private */
export type _DeepNonNullableObject<T> = {
[P in keyof T]-?: DeepNonNullable<NonNullable<T[P]>>;
};
/**
* DeepPartial
* @desc Partial that works for deeply nested structure
* @example
* // Expect: {
* // first?: {
* // second?: {
* // name?: string;
* // };
* // };
* // }
* type NestedProps = {
* first: {
* second: {
* name: string;
* };
* };
* };
* type PartialNestedProps = DeepPartial<NestedProps>;
*/
export type DeepPartial<T> = { [P in keyof T]?: _DeepPartial<T[P]> };
/** @private */
export type _DeepPartial<T> = T extends Function
? T
: T extends Array<infer U>
? _DeepPartialArray<U>
: T extends object
? DeepPartial<T>
: T | undefined;
/** @private */
// tslint:disable-next-line:class-name
export interface _DeepPartialArray<T> extends Array<_DeepPartial<T>> {}
/**
* Brand
* @desc Define nominal type of U based on type of T. Similar to Opaque types in Flow.
* @example
* type USD = Brand<number, "USD">
* type EUR = Brand<number, "EUR">
*
* const tax = 5 as USD;
* const usd = 10 as USD;
* const eur = 10 as EUR;
*
* function gross(net: USD): USD {
* return (net + tax) as USD;
* }
*
* // Expect: No compile error
* gross(usd);
* // Expect: Compile error (Type '"EUR"' is not assignable to type '"USD"'.)
* gross(eur);
*/
export type Brand<T, U> = T & { __brand: U };
/**
* Optional
* @desc From `T` make a set of properties by key `K` become optional
* @example
* type Props = {
* name: string;
* age: number;
* visible: boolean;
* };
*
* // Expect: { name?: string; age?: number; visible?: boolean; }
* type Props = Optional<Props>;
*
* // Expect: { name: string; age?: number; visible?: boolean; }
* type Props = Optional<Props, 'age' | 'visible'>;
*/
export type Optional<T extends object, K extends keyof T = keyof T> = Omit<
T,
K
> &
Partial<Pick<T, K>>;
/**
* ValuesType
* @desc Get the union type of all the values in an object, array or array-like type `T`
* @example
* type Props = { name: string; age: number; visible: boolean };
* // Expect: string | number | boolean
* type PropsValues = ValuesType<Props>;
*
* type NumberArray = number[];
* // Expect: number
* type NumberItems = ValuesType<NumberArray>;
*
* type ReadonlySymbolArray = readonly symbol[];
* // Expect: symbol
* type SymbolItems = ValuesType<ReadonlySymbolArray>;
*
* type NumberTuple = [1, 2];
* // Expect: 1 | 2
* type NumberUnion = ValuesType<NumberTuple>;
*
* type ReadonlyNumberTuple = readonly [1, 2];
* // Expect: 1 | 2
* type AnotherNumberUnion = ValuesType<NumberTuple>;
*
* type BinaryArray = Uint8Array;
* // Expect: number
* type BinaryItems = ValuesType<BinaryArray>;
*/
export type ValuesType<
T extends ReadonlyArray<any> | ArrayLike<any> | Record<any, any>
> = T extends ReadonlyArray<any>
? T[number]
: T extends ArrayLike<any>
? T[number]
: T extends object
? T[keyof T]
: never;
/**
* Required
* @desc From `T` make a set of properties by key `K` become required
* @example
* type Props = {
* name?: string;
* age?: number;
* visible?: boolean;
* };
*
* // Expect: { name: string; age: number; visible: boolean; }
* type Props = Required<Props>;
*
* // Expect: { name?: string; age: number; visible: boolean; }
* type Props = Required<Props, 'age' | 'visible'>;
*/
export type AugmentedRequired<
T extends object,
K extends keyof T = keyof T
> = Omit<T, K> & Required<Pick<T, K>>;
/**
* UnionToIntersection
* @desc Get intersection type given union type `U`
* Credit: jcalz
* @see https://stackoverflow.com/a/50375286/7381355
* @example
* // Expect: { name: string } & { age: number } & { visible: boolean }
* UnionToIntersection<{ name: string } | { age: number } | { visible: boolean }>
*/
export type UnionToIntersection<U> = (U extends any
? (k: U) => void
: never) extends (k: infer I) => void
? I
: never;
/**
* Mutable
* @desc From `T` make all properties become mutable
* @example
* type Props = {
* readonly name: string;
* readonly age: number;
* readonly visible: boolean;
* };
*
* // Expect: { name: string; age: number; visible: boolean; }
* Mutable<Props>;
*/
export type Mutable<T> = { -readonly [P in keyof T]: T[P] };
export type Writable<T> = Mutable<T>;