-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.ts
949 lines (898 loc) · 29.4 KB
/
index.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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
import type {StrictEqualUsingBranding} from './branding'
import type {
ExpectAny,
ExpectArray,
ExpectBigInt,
ExpectBoolean,
ExpectFunction,
ExpectNever,
ExpectNull,
ExpectNullable,
ExpectNumber,
ExpectObject,
ExpectString,
ExpectSymbol,
ExpectUndefined,
ExpectUnknown,
ExpectVoid,
MismatchInfo,
Scolder,
} from './messages'
import type {
ConstructorOverloadParameters,
OverloadParameters,
OverloadReturnTypes,
OverloadsNarrowedByParameters,
} from './overloads'
import type {AValue, Extends, MismatchArgs, StrictEqualUsingTSInternalIdenticalToOperator} from './utils'
export * from './branding' // backcompat, consider removing in next major version
export * from './messages' // backcompat, consider removing in next major version
export * from './overloads'
export * from './utils' // backcompat, consider removing in next major version
/**
* Represents the positive assertion methods available for type checking in the
* {@linkcode expectTypeOf()} utility.
*/
export interface PositiveExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {positive: true; branded: false}> {
toEqualTypeOf: {
/**
* Uses TypeScript's internal technique to check for type "identicalness".
*
* It will check if the types are fully equal to each other.
* It will not fail if two objects have different values, but the same type.
* It will fail however if an object is missing a property.
*
* **_Unexpected failure_**? For a more permissive but less performant
* check that accommodates for equivalent intersection types,
* use {@linkcode branded | .branded.toEqualTypeOf()}.
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
*
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
*
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
* ```
*
* @param value - The value to compare against the expected type.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<
Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true
? unknown
: MismatchInfo<Actual, Expected>,
>(
value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>
): true
/**
* Uses TypeScript's internal technique to check for type "identicalness".
*
* It will check if the types are fully equal to each other.
* It will not fail if two objects have different values, but the same type.
* It will fail however if an object is missing a property.
*
* **_Unexpected failure_**? For a more permissive but less performant
* check that accommodates for equivalent intersection types,
* use {@linkcode branded | .branded.toEqualTypeOf()}.
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
*
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
*
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
* ```
*
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<
Expected extends StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected> extends true
? unknown
: MismatchInfo<Actual, Expected>,
>(
...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, true>
): true
}
toMatchTypeOf: {
/**
* A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()}
* that allows for extra properties.
* This is roughly equivalent to an `extends` constraint
* in a function type argument.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
* ```
*
* @param value - The value to compare against the expected type.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(
value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>
): true
/**
* A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()}
* that allows for extra properties.
* This is roughly equivalent to an `extends` constraint
* in a function type argument.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
* ```
*
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected extends Extends<Actual, Expected> extends true ? unknown : MismatchInfo<Actual, Expected>>(
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, true>
): true
}
/**
* Checks whether an object has a given property.
*
* @example
* <caption>check that properties exist</caption>
* ```ts
* const obj = { a: 1, b: '' }
*
* expectTypeOf(obj).toHaveProperty('a')
*
* expectTypeOf(obj).not.toHaveProperty('c')
* ```
*
* @param key - The property key to check for.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
toHaveProperty: <KeyType extends keyof Actual>(
key: KeyType,
...MISMATCH: MismatchArgs<Extends<KeyType, keyof Actual>, true>
) => KeyType extends keyof Actual ? PositiveExpectTypeOf<Actual[KeyType]> : true
/**
* Inverts the result of the following assertions.
*
* @example
* ```ts
* expectTypeOf({ a: 1 }).not.toMatchTypeOf({ b: 1 })
* ```
*/
not: NegativeExpectTypeOf<Actual>
/**
* Intersection types can cause issues with
* {@linkcode toEqualTypeOf | .toEqualTypeOf()}:
* ```ts
* // ❌ The following line doesn't compile, even though the types are arguably the same.
* expectTypeOf<{ a: 1 } & { b: 2 }>().toEqualTypeOf<{ a: 1; b: 2 }>()
* ```
* This helper works around this problem by using
* a more permissive but less performant check.
*
* __Note__: This comes at a performance cost, and can cause the compiler
* to 'give up' if used with excessively deep types, so use sparingly.
*
* @see {@link https://github.com/mmkal/expect-type/pull/21 | Reference}
*/
branded: {
/**
* Uses TypeScript's internal technique to check for type "identicalness".
*
* It will check if the types are fully equal to each other.
* It will not fail if two objects have different values, but the same type.
* It will fail however if an object is missing a property.
*
* **_Unexpected failure_**? For a more permissive but less performant
* check that accommodates for equivalent intersection types,
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
*
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
*
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
* ```
*
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
toEqualTypeOf: <
Expected extends StrictEqualUsingBranding<Actual, Expected> extends true
? unknown
: MismatchInfo<Actual, Expected>,
>(
...MISMATCH: MismatchArgs<StrictEqualUsingBranding<Actual, Expected>, true>
) => true
}
}
/**
* Represents the negative expectation type for the {@linkcode Actual} type.
*/
export interface NegativeExpectTypeOf<Actual> extends BaseExpectTypeOf<Actual, {positive: false}> {
toEqualTypeOf: {
/**
* Uses TypeScript's internal technique to check for type "identicalness".
*
* It will check if the types are fully equal to each other.
* It will not fail if two objects have different values, but the same type.
* It will fail however if an object is missing a property.
*
* **_Unexpected failure_**? For a more permissive but less performant
* check that accommodates for equivalent intersection types,
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
*
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
*
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
* ```
*
* @param value - The value to compare against the expected type.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected>(
value: Expected & AValue,
...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>
): true
/**
* Uses TypeScript's internal technique to check for type "identicalness".
*
* It will check if the types are fully equal to each other.
* It will not fail if two objects have different values, but the same type.
* It will fail however if an object is missing a property.
*
* **_Unexpected failure_**? For a more permissive but less performant
* check that accommodates for equivalent intersection types,
* use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}.
* @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
*
* expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
*
* expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
* ```
*
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected>(...MISMATCH: MismatchArgs<StrictEqualUsingTSInternalIdenticalToOperator<Actual, Expected>, false>): true
}
toMatchTypeOf: {
/**
* A less strict version of
* {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()}
* that allows for extra properties.
* This is roughly equivalent to an `extends` constraint
* in a function type argument.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
* ```
*
* @param value - The value to compare against the expected type.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected>(
value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`.
...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>
): true
/**
* A less strict version of
* {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()}
* that allows for extra properties.
* This is roughly equivalent to an `extends` constraint
* in a function type argument.
*
* @example
* <caption>Using generic type argument syntax</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>()
* ```
*
* @example
* <caption>Using inferred type syntax by passing a value</caption>
* ```ts
* expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 })
* ```
*
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
<Expected>(...MISMATCH: MismatchArgs<Extends<Actual, Expected>, false>): true
}
/**
* Checks whether an object has a given property.
*
* @example
* <caption>check that properties exist</caption>
* ```ts
* const obj = { a: 1, b: '' }
*
* expectTypeOf(obj).toHaveProperty('a')
*
* expectTypeOf(obj).not.toHaveProperty('c')
* ```
*
* @param key - The property key to check for.
* @param MISMATCH - The mismatch arguments.
* @returns `true`.
*/
toHaveProperty: <KeyType extends string | number | symbol>(
key: KeyType,
...MISMATCH: MismatchArgs<Extends<KeyType, keyof Actual>, false>
) => true
}
/**
* Represents a conditional type that selects either
* {@linkcode PositiveExpectTypeOf} or {@linkcode NegativeExpectTypeOf} based
* on the value of the `positive` property in the {@linkcode Options} type.
*/
export type ExpectTypeOf<Actual, Options extends {positive: boolean}> = Options['positive'] extends true
? PositiveExpectTypeOf<Actual>
: NegativeExpectTypeOf<Actual>
/**
* Represents the base interface for the
* {@linkcode expectTypeOf()} function.
* Provides a set of assertion methods to perform type checks on a value.
*/
export interface BaseExpectTypeOf<Actual, Options extends {positive: boolean}> {
/**
* Checks whether the type of the value is `any`.
*/
toBeAny: Scolder<ExpectAny<Actual>, Options>
/**
* Checks whether the type of the value is `unknown`.
*/
toBeUnknown: Scolder<ExpectUnknown<Actual>, Options>
/**
* Checks whether the type of the value is `never`.
*/
toBeNever: Scolder<ExpectNever<Actual>, Options>
/**
* Checks whether the type of the value is `function`.
*/
toBeFunction: Scolder<ExpectFunction<Actual>, Options>
/**
* Checks whether the type of the value is `object`.
*/
toBeObject: Scolder<ExpectObject<Actual>, Options>
/**
* Checks whether the type of the value is an {@linkcode Array}.
*/
toBeArray: Scolder<ExpectArray<Actual>, Options>
/**
* Checks whether the type of the value is `number`.
*/
toBeNumber: Scolder<ExpectNumber<Actual>, Options>
/**
* Checks whether the type of the value is `string`.
*/
toBeString: Scolder<ExpectString<Actual>, Options>
/**
* Checks whether the type of the value is `boolean`.
*/
toBeBoolean: Scolder<ExpectBoolean<Actual>, Options>
/**
* Checks whether the type of the value is `void`.
*/
toBeVoid: Scolder<ExpectVoid<Actual>, Options>
/**
* Checks whether the type of the value is `symbol`.
*/
toBeSymbol: Scolder<ExpectSymbol<Actual>, Options>
/**
* Checks whether the type of the value is `null`.
*/
toBeNull: Scolder<ExpectNull<Actual>, Options>
/**
* Checks whether the type of the value is `undefined`.
*/
toBeUndefined: Scolder<ExpectUndefined<Actual>, Options>
/**
* Checks whether the type of the value is `null` or `undefined`.
*/
toBeNullable: Scolder<ExpectNullable<Actual>, Options>
/**
* Checks whether the type of the value is **`bigint`**.
*
* @example
* <caption>#### Distinguish between **`number`** and **`bigint`**</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* const aVeryBigInteger = 10n ** 100n
*
* expectTypeOf(aVeryBigInteger).not.toBeNumber()
*
* expectTypeOf(aVeryBigInteger).toBeBigInt()
* ```
*
* @since 1.1.0
*/
toBeBigInt: Scolder<ExpectBigInt<Actual>, Options>
/**
* Checks whether a function is callable with the given parameters.
*
* __Note__: You cannot negate this assertion with
* {@linkcode PositiveExpectTypeOf.not | .not}, you need to use
* `ts-expect-error` instead.
*
* @example
* ```ts
* const f = (a: number) => [a, a]
*
* expectTypeOf(f).toBeCallableWith(1)
* ```
*
* __Known Limitation__: This assertion will likely fail if you try to use it
* with a generic function or an overload.
* @see {@link https://github.com/mmkal/expect-type/issues/50 | This issue} for an example and a workaround.
*
* @param args - The arguments to check for callability.
* @returns `true`.
*/
toBeCallableWith: Options['positive'] extends true
? <Args extends OverloadParameters<Actual>>(
...args: Args
) => ExpectTypeOf<OverloadsNarrowedByParameters<Actual, Args>, Options>
: never
/**
* Checks whether a class is constructible with the given parameters.
*
* @example
* ```ts
* expectTypeOf(Date).toBeConstructibleWith('1970')
*
* expectTypeOf(Date).toBeConstructibleWith(0)
*
* expectTypeOf(Date).toBeConstructibleWith(new Date())
*
* expectTypeOf(Date).toBeConstructibleWith()
* ```
*
* @param args - The arguments to check for constructibility.
* @returns `true`.
*/
toBeConstructibleWith: Options['positive'] extends true
? <Args extends ConstructorOverloadParameters<Actual>>(...args: Args) => true
: never
/**
* Equivalent to the {@linkcode Extract} utility type.
* Helps narrow down complex union types.
*
* @example
* ```ts
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
*
* interface CSSProperties {
* margin?: string
* padding?: string
* }
*
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
* return {}
* }
*
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .extract<{ xs?: any }>() // extracts the last type from a union
* .toEqualTypeOf<{
* xs?: CSSProperties
* sm?: CSSProperties
* md?: CSSProperties
* }>()
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .extract<unknown[]>() // extracts an array from a union
* .toEqualTypeOf<CSSProperties[]>()
* ```
*
* __Note__: If no type is found in the union, it will return `never`.
*
* @param v - The type to extract from the union.
* @returns The type after extracting the type from the union.
*/
extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, Options>
/**
* Equivalent to the {@linkcode Exclude} utility type.
* Removes types from a union.
*
* @example
* ```ts
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
*
* interface CSSProperties {
* margin?: string
* padding?: string
* }
*
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
* return {}
* }
*
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .exclude<unknown[]>()
* .exclude<{ xs?: unknown }>() // or just `.exclude<unknown[] | { xs?: unknown }>()`
* .toEqualTypeOf<CSSProperties>()
* ```
*/
exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, Options>
/**
* Equivalent to the {@linkcode Pick} utility type.
* Helps select a subset of properties from an object type.
*
* @example
* ```ts
* interface Person {
* name: string
* age: number
* }
*
* expectTypeOf<Person>()
* .pick<'name'>()
* .toEqualTypeOf<{ name: string }>()
* ```
*
* @param keyToPick - The property key to pick.
* @returns The type after picking the property.
*/
pick: <KeyToPick extends keyof Actual>(keyToPick?: KeyToPick) => ExpectTypeOf<Pick<Actual, KeyToPick>, Options>
/**
* Equivalent to the {@linkcode Omit} utility type.
* Helps remove a subset of properties from an object type.
*
* @example
* ```ts
* interface Person {
* name: string
* age: number
* }
*
* expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{ age: number }>()
* ```
*
* @param keyToOmit - The property key to omit.
* @returns The type after omitting the property.
*/
omit: <KeyToOmit extends keyof Actual | (PropertyKey & Record<never, never>)>(
keyToOmit?: KeyToOmit,
) => ExpectTypeOf<Omit<Actual, KeyToOmit>, Options>
/**
* Extracts a certain function argument with `.parameter(number)` call to
* perform other assertions on it.
*
* @example
* ```ts
* function foo(a: number, b: string) {
* return [a, b]
* }
*
* expectTypeOf(foo).parameter(0).toBeNumber()
*
* expectTypeOf(foo).parameter(1).toBeString()
* ```
*
* @param index - The index of the parameter to extract.
* @returns The extracted parameter type.
*/
parameter: <Index extends number>(index: Index) => ExpectTypeOf<OverloadParameters<Actual>[Index], Options>
/**
* Equivalent to the {@linkcode Parameters} utility type.
* Extracts function parameters to perform assertions on its value.
* Parameters are returned as an array.
*
* @example
* ```ts
* function noParam() {}
*
* function hasParam(s: string) {}
*
* expectTypeOf(noParam).parameters.toEqualTypeOf<[]>()
*
* expectTypeOf(hasParam).parameters.toEqualTypeOf<[string]>()
* ```
*/
parameters: ExpectTypeOf<OverloadParameters<Actual>, Options>
/**
* Equivalent to the {@linkcode ConstructorParameters} utility type.
* Extracts constructor parameters as an array of values and
* perform assertions on them with this method.
*
* For overloaded constructors it will return a union of all possible parameter-tuples.
*
* @example
* ```ts
* expectTypeOf(Date).constructorParameters.toEqualTypeOf<
* [] | [string | number | Date]
* >()
* ```
*/
constructorParameters: ExpectTypeOf<ConstructorOverloadParameters<Actual>, Options>
/**
* Equivalent to the {@linkcode ThisParameterType} utility type.
* Extracts the `this` parameter of a function to
* perform assertions on its value.
*
* @example
* ```ts
* function greet(this: { name: string }, message: string) {
* return `Hello ${this.name}, here's your message: ${message}`
* }
*
* expectTypeOf(greet).thisParameter.toEqualTypeOf<{ name: string }>()
* ```
*/
thisParameter: ExpectTypeOf<ThisParameterType<Actual>, Options>
/**
* Equivalent to the {@linkcode InstanceType} utility type.
* Extracts the instance type of a class to perform assertions on.
*
* @example
* ```ts
* expectTypeOf(Date).instance.toHaveProperty('toISOString')
* ```
*/
instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf<I, Options> : never
/**
* Equivalent to the {@linkcode ReturnType} utility type.
* Extracts the return type of a function.
*
* @example
* ```ts
* expectTypeOf(() => {}).returns.toBeVoid()
*
* expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2])
* ```
*/
returns: Actual extends Function ? ExpectTypeOf<OverloadReturnTypes<Actual>, Options> : never
/**
* Extracts resolved value of a Promise,
* so you can perform other assertions on it.
*
* @example
* ```ts
* async function asyncFunc() {
* return 123
* }
*
* expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
*
* expectTypeOf(Promise.resolve('string')).resolves.toBeString()
* ```
*
* Type Equivalent:
* ```ts
* type Resolves<PromiseType> = PromiseType extends PromiseLike<infer ResolvedType>
* ? ResolvedType
* : never
* ```
*/
resolves: Actual extends PromiseLike<infer ResolvedType> ? ExpectTypeOf<ResolvedType, Options> : never
/**
* Extracts array item type to perform assertions on.
*
* @example
* ```ts
* expectTypeOf([1, 2, 3]).items.toEqualTypeOf<number>()
*
* expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf<string>()
* ```
*
* __Type Equivalent__:
* ```ts
* type Items<ArrayType> = ArrayType extends ArrayLike<infer ItemType>
* ? ItemType
* : never
* ```
*/
items: Actual extends ArrayLike<infer ItemType> ? ExpectTypeOf<ItemType, Options> : never
/**
* Extracts the type guarded by a function to perform assertions on.
*
* @example
* ```ts
* function isString(v: any): v is string {
* return typeof v === 'string'
* }
*
* expectTypeOf(isString).guards.toBeString()
* ```
*/
guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf<T, Options> : never
/**
* Extracts the type asserted by a function to perform assertions on.
*
* @example
* ```ts
* function assertNumber(v: any): asserts v is number {
* if (typeof v !== 'number')
* throw new TypeError('Nope !')
* }
*
* expectTypeOf(assertNumber).asserts.toBeNumber()
* ```
*/
asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T
? // Guard methods `(v: any) => asserts v is T` does not actually defines a return type. Thus, any function taking 1 argument matches the signature before.
// In case the inferred assertion type `R` could not be determined (so, `unknown`), consider the function as a non-guard, and return a `never` type.
// See https://github.com/microsoft/TypeScript/issues/34636
unknown extends T
? never
: ExpectTypeOf<T, Options>
: never
}
const fn: any = () => true
/**
* Represents a function that allows asserting the expected type of a value.
*/
export type _ExpectTypeOf = {
/**
* Asserts the expected type of a value.
*
* @param actual - The actual value being asserted.
* @returns An object representing the expected type assertion.
*/
<Actual>(actual: Actual): ExpectTypeOf<Actual, {positive: true; branded: false}>
/**
* Asserts the expected type of a value without providing an actual value.
*
* @returns An object representing the expected type assertion.
*/
<Actual>(): ExpectTypeOf<Actual, {positive: true; branded: false}>
}
/**
* Similar to Jest's `expect`, but with type-awareness.
* Gives you access to a number of type-matchers that let you make assertions about the
* form of a reference or generic type parameter.
*
* @example
* ```ts
* import { foo, bar } from '../foo'
* import { expectTypeOf } from 'expect-type'
*
* test('foo types', () => {
* // make sure `foo` has type { a: number }
* expectTypeOf(foo).toMatchTypeOf({ a: 1 })
* expectTypeOf(foo).toHaveProperty('a').toBeNumber()
*
* // make sure `bar` is a function taking a string:
* expectTypeOf(bar).parameter(0).toBeString()
* expectTypeOf(bar).returns.not.toBeAny()
* })
* ```
*
* @description
* See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
*/
export const expectTypeOf: _ExpectTypeOf = <Actual>(
_actual?: Actual,
): ExpectTypeOf<Actual, {positive: true; branded: false}> => {
const nonFunctionProperties = [
'parameters',
'returns',
'resolves',
'not',
'items',
'constructorParameters',
'thisParameter',
'instance',
'guards',
'asserts',
'branded',
] as const
type Keys = keyof PositiveExpectTypeOf<any> | keyof NegativeExpectTypeOf<any>
type FunctionsDict = Record<Exclude<Keys, (typeof nonFunctionProperties)[number]>, any>
const obj: FunctionsDict = {
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
toBeAny: fn,
toBeUnknown: fn,
toBeNever: fn,
toBeFunction: fn,
toBeObject: fn,
toBeArray: fn,
toBeString: fn,
toBeNumber: fn,
toBeBoolean: fn,
toBeVoid: fn,
toBeSymbol: fn,
toBeNull: fn,
toBeUndefined: fn,
toBeNullable: fn,
toBeBigInt: fn,
toMatchTypeOf: fn,
toEqualTypeOf: fn,
toBeConstructibleWith: fn,
toBeCallableWith: expectTypeOf,
extract: expectTypeOf,
exclude: expectTypeOf,
pick: expectTypeOf,
omit: expectTypeOf,
toHaveProperty: expectTypeOf,
parameter: expectTypeOf,
}
const getterProperties: readonly Keys[] = nonFunctionProperties
getterProperties.forEach((prop: Keys) => Object.defineProperty(obj, prop, {get: () => expectTypeOf({})}))
return obj as ExpectTypeOf<Actual, {positive: true; branded: false}>
}