@visulima/package 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2751 +0,0 @@
1
- import { WriteJsonOptions } from '@visulima/fs';
2
- import { a as JsonValue, J as JsonObject } from './json-value.d-DU4PzU4Z.js';
3
- import { InstallPackageOptions } from '@antfu/install-pkg';
4
- import { Package } from 'normalize-package-data';
5
-
6
- /**
7
- Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
8
-
9
- @category Type
10
- */
11
- type Primitive =
12
- | null
13
- | undefined
14
- | string
15
- | number
16
- | boolean
17
- | symbol
18
- | bigint;
19
-
20
- /**
21
- Returns a boolean for whether the given type is `any`.
22
-
23
- @link https://stackoverflow.com/a/49928360/1490091
24
-
25
- Useful in type utilities, such as disallowing `any`s to be passed to a function.
26
-
27
- @example
28
- ```
29
- import type {IsAny} from 'type-fest';
30
-
31
- const typedObject = {a: 1, b: 2} as const;
32
- const anyObject: any = {a: 1, b: 2};
33
-
34
- function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) {
35
- return obj[key];
36
- }
37
-
38
- const typedA = get(typedObject, 'a');
39
- //=> 1
40
-
41
- const anyA = get(anyObject, 'a');
42
- //=> any
43
- ```
44
-
45
- @category Type Guard
46
- @category Utilities
47
- */
48
- type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
49
-
50
- /**
51
- Returns a boolean for whether the given key is an optional key of type.
52
-
53
- This is useful when writing utility types or schema validators that need to differentiate `optional` keys.
54
-
55
- @example
56
- ```
57
- import type {IsOptionalKeyOf} from 'type-fest';
58
-
59
- interface User {
60
- name: string;
61
- surname: string;
62
-
63
- luckyNumber?: number;
64
- }
65
-
66
- interface Admin {
67
- name: string;
68
- surname?: string;
69
- }
70
-
71
- type T1 = IsOptionalKeyOf<User, 'luckyNumber'>;
72
- //=> true
73
-
74
- type T2 = IsOptionalKeyOf<User, 'name'>;
75
- //=> false
76
-
77
- type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>;
78
- //=> boolean
79
-
80
- type T4 = IsOptionalKeyOf<User | Admin, 'name'>;
81
- //=> false
82
-
83
- type T5 = IsOptionalKeyOf<User | Admin, 'surname'>;
84
- //=> boolean
85
- ```
86
-
87
- @category Type Guard
88
- @category Utilities
89
- */
90
- type IsOptionalKeyOf<Type extends object, Key extends keyof Type> =
91
- IsAny<Type | Key> extends true ? never
92
- : Key extends keyof Type
93
- ? Type extends Record<Key, Type[Key]>
94
- ? false
95
- : true
96
- : false;
97
-
98
- /**
99
- Extract all optional keys from the given type.
100
-
101
- This is useful when you want to create a new type that contains different type values for the optional keys only.
102
-
103
- @example
104
- ```
105
- import type {OptionalKeysOf, Except} from 'type-fest';
106
-
107
- interface User {
108
- name: string;
109
- surname: string;
110
-
111
- luckyNumber?: number;
112
- }
113
-
114
- const REMOVE_FIELD = Symbol('remove field symbol');
115
- type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
116
- [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
117
- };
118
-
119
- const update1: UpdateOperation<User> = {
120
- name: 'Alice'
121
- };
122
-
123
- const update2: UpdateOperation<User> = {
124
- name: 'Bob',
125
- luckyNumber: REMOVE_FIELD
126
- };
127
- ```
128
-
129
- @category Utilities
130
- */
131
- type OptionalKeysOf<Type extends object> =
132
- Type extends unknown // For distributing `Type`
133
- ? (keyof {[Key in keyof Type as
134
- IsOptionalKeyOf<Type, Key> extends false
135
- ? never
136
- : Key
137
- ]: never
138
- }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf<Type>` is always assignable to `keyof Type`
139
- : never; // Should never happen
140
-
141
- /**
142
- Extract all required keys from the given type.
143
-
144
- This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...
145
-
146
- @example
147
- ```
148
- import type {RequiredKeysOf} from 'type-fest';
149
-
150
- declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
151
-
152
- interface User {
153
- name: string;
154
- surname: string;
155
-
156
- luckyNumber?: number;
157
- }
158
-
159
- const validator1 = createValidation<User>('name', value => value.length < 25);
160
- const validator2 = createValidation<User>('surname', value => value.length < 25);
161
- ```
162
-
163
- @category Utilities
164
- */
165
- type RequiredKeysOf<Type extends object> =
166
- Type extends unknown // For distributing `Type`
167
- ? Exclude<keyof Type, OptionalKeysOf<Type>>
168
- : never; // Should never happen
169
-
170
- /**
171
- Returns a boolean for whether the given type is `never`.
172
-
173
- @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
174
- @link https://stackoverflow.com/a/53984913/10292952
175
- @link https://www.zhenghao.io/posts/ts-never
176
-
177
- Useful in type utilities, such as checking if something does not occur.
178
-
179
- @example
180
- ```
181
- import type {IsNever, And} from 'type-fest';
182
-
183
- // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts
184
- type AreStringsEqual<A extends string, B extends string> =
185
- And<
186
- IsNever<Exclude<A, B>> extends true ? true : false,
187
- IsNever<Exclude<B, A>> extends true ? true : false
188
- >;
189
-
190
- type EndIfEqual<I extends string, O extends string> =
191
- AreStringsEqual<I, O> extends true
192
- ? never
193
- : void;
194
-
195
- function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> {
196
- if (input === output) {
197
- process.exit(0);
198
- }
199
- }
200
-
201
- endIfEqual('abc', 'abc');
202
- //=> never
203
-
204
- endIfEqual('abc', '123');
205
- //=> void
206
- ```
207
-
208
- @category Type Guard
209
- @category Utilities
210
- */
211
- type IsNever<T> = [T] extends [never] ? true : false;
212
-
213
- /**
214
- An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
215
-
216
- Use-cases:
217
- - You can use this in combination with `Is*` types to create an if-else-like experience. For example, `If<IsAny<any>, 'is any', 'not any'>`.
218
-
219
- Note:
220
- - Returns a union of if branch and else branch if the given type is `boolean` or `any`. For example, `If<boolean, 'Y', 'N'>` will return `'Y' | 'N'`.
221
- - Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
222
-
223
- @example
224
- ```
225
- import {If} from 'type-fest';
226
-
227
- type A = If<true, 'yes', 'no'>;
228
- //=> 'yes'
229
-
230
- type B = If<false, 'yes', 'no'>;
231
- //=> 'no'
232
-
233
- type C = If<boolean, 'yes', 'no'>;
234
- //=> 'yes' | 'no'
235
-
236
- type D = If<any, 'yes', 'no'>;
237
- //=> 'yes' | 'no'
238
-
239
- type E = If<never, 'yes', 'no'>;
240
- //=> 'no'
241
- ```
242
-
243
- @example
244
- ```
245
- import {If, IsAny, IsNever} from 'type-fest';
246
-
247
- type A = If<IsAny<unknown>, 'is any', 'not any'>;
248
- //=> 'not any'
249
-
250
- type B = If<IsNever<never>, 'is never', 'not never'>;
251
- //=> 'is never'
252
- ```
253
-
254
- @example
255
- ```
256
- import {If, IsEqual} from 'type-fest';
257
-
258
- type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
259
-
260
- type A = IfEqual<string, string, 'equal', 'not equal'>;
261
- //=> 'equal'
262
-
263
- type B = IfEqual<string, number, 'equal', 'not equal'>;
264
- //=> 'not equal'
265
- ```
266
-
267
- @category Type Guard
268
- @category Utilities
269
- */
270
- type If<Type extends boolean, IfBranch, ElseBranch> =
271
- IsNever<Type> extends true
272
- ? ElseBranch
273
- : Type extends true
274
- ? IfBranch
275
- : ElseBranch;
276
-
277
- /**
278
- Represents an array with `unknown` value.
279
-
280
- Use case: You want a type that all arrays can be assigned to, but you don't care about the value.
281
-
282
- @example
283
- ```
284
- import type {UnknownArray} from 'type-fest';
285
-
286
- type IsArray<T> = T extends UnknownArray ? true : false;
287
-
288
- type A = IsArray<['foo']>;
289
- //=> true
290
-
291
- type B = IsArray<readonly number[]>;
292
- //=> true
293
-
294
- type C = IsArray<string>;
295
- //=> false
296
- ```
297
-
298
- @category Type
299
- @category Array
300
- */
301
- type UnknownArray = readonly unknown[];
302
-
303
- /**
304
- Matches any primitive, `void`, `Date`, or `RegExp` value.
305
- */
306
- type BuiltIns = Primitive | void | Date | RegExp;
307
-
308
- /**
309
- Matches non-recursive types.
310
- */
311
- type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown);
312
-
313
- /**
314
- Returns a boolean for whether the given `boolean` is not `false`.
315
- */
316
- type IsNotFalse<T extends boolean> = [T] extends [false] ? false : true;
317
-
318
- /**
319
- Returns a boolean for whether A is false.
320
-
321
- @example
322
- ```
323
- Not<true>;
324
- //=> false
325
-
326
- Not<false>;
327
- //=> true
328
- ```
329
- */
330
- type Not<A extends boolean> = A extends true
331
- ? false
332
- : A extends false
333
- ? true
334
- : never;
335
-
336
- /**
337
- An if-else-like type that resolves depending on whether the given type is `any` or `never`.
338
-
339
- @example
340
- ```
341
- // When `T` is a NOT `any` or `never` (like `string`) => Returns `IfNotAnyOrNever` branch
342
- type A = IfNotAnyOrNever<string, 'VALID', 'IS_ANY', 'IS_NEVER'>;
343
- //=> 'VALID'
344
-
345
- // When `T` is `any` => Returns `IfAny` branch
346
- type B = IfNotAnyOrNever<any, 'VALID', 'IS_ANY', 'IS_NEVER'>;
347
- //=> 'IS_ANY'
348
-
349
- // When `T` is `never` => Returns `IfNever` branch
350
- type C = IfNotAnyOrNever<never, 'VALID', 'IS_ANY', 'IS_NEVER'>;
351
- //=> 'IS_NEVER'
352
- ```
353
- */
354
- type IfNotAnyOrNever<T, IfNotAnyOrNever, IfAny = any, IfNever = never> =
355
- If<IsAny<T>, IfAny, If<IsNever<T>, IfNever, IfNotAnyOrNever>>;
356
-
357
- /**
358
- Returns a boolean for whether the given type is `any` or `never`.
359
-
360
- This type can be better to use than {@link IfNotAnyOrNever `IfNotAnyOrNever`} in recursive types because it does not evaluate any branches.
361
-
362
- @example
363
- ```
364
- // When `T` is a NOT `any` or `never` (like `string`) => Returns `false`
365
- type A = IsAnyOrNever<string>;
366
- //=> false
367
-
368
- // When `T` is `any` => Returns `true`
369
- type B = IsAnyOrNever<any>;
370
- //=> true
371
-
372
- // When `T` is `never` => Returns `true`
373
- type C = IsAnyOrNever<never>;
374
- //=> true
375
- ```
376
- */
377
- type IsAnyOrNever<T> = IsNotFalse<IsAny<T> | IsNever<T>>;
378
-
379
- /**
380
- Indicates the value of `exactOptionalPropertyTypes` compiler option.
381
- */
382
- type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extends [string?]
383
- ? false
384
- : true;
385
-
386
- /**
387
- Returns the static, fixed-length portion of the given array, excluding variable-length parts.
388
-
389
- @example
390
- ```
391
- type A = [string, number, boolean, ...string[]];
392
- type B = StaticPartOfArray<A>;
393
- //=> [string, number, boolean]
394
- ```
395
- */
396
- type StaticPartOfArray<T extends UnknownArray, Result extends UnknownArray = []> =
397
- T extends unknown
398
- ? number extends T['length'] ?
399
- T extends readonly [infer U, ...infer V]
400
- ? StaticPartOfArray<V, [...Result, U]>
401
- : Result
402
- : T
403
- : never; // Should never happen
404
-
405
- /**
406
- Returns the variable, non-fixed-length portion of the given array, excluding static-length parts.
407
-
408
- @example
409
- ```
410
- type A = [string, number, boolean, ...string[]];
411
- type B = VariablePartOfArray<A>;
412
- //=> string[]
413
- ```
414
- */
415
- type VariablePartOfArray<T extends UnknownArray> =
416
- T extends unknown
417
- ? T extends readonly [...StaticPartOfArray<T>, ...infer U]
418
- ? U
419
- : []
420
- : never;
421
-
422
- /**
423
- Transforms a tuple type by replacing it's rest element with a single element that has the same type as the rest element, while keeping all the non-rest elements intact.
424
-
425
- @example
426
- ```
427
- type A = CollapseRestElement<[string, string, ...number[]]>;
428
- //=> [string, string, number]
429
-
430
- type B = CollapseRestElement<[...string[], number, number]>;
431
- //=> [string, number, number]
432
-
433
- type C = CollapseRestElement<[string, string, ...Array<number | bigint>]>;
434
- //=> [string, string, number | bigint]
435
-
436
- type D = CollapseRestElement<[string, number]>;
437
- //=> [string, number]
438
- ```
439
-
440
- Note: Optional modifiers (`?`) are removed from elements unless the `exactOptionalPropertyTypes` compiler option is disabled. When disabled, there's an additional `| undefined` for optional elements.
441
-
442
- @example
443
- ```
444
- // `exactOptionalPropertyTypes` enabled
445
- type A = CollapseRestElement<[string?, string?, ...number[]]>;
446
- //=> [string, string, number]
447
-
448
- // `exactOptionalPropertyTypes` disabled
449
- type B = CollapseRestElement<[string?, string?, ...number[]]>;
450
- //=> [string | undefined, string | undefined, number]
451
- ```
452
- */
453
- type CollapseRestElement<TArray extends UnknownArray> = IfNotAnyOrNever<TArray, _CollapseRestElement<TArray>>;
454
-
455
- type _CollapseRestElement<
456
- TArray extends UnknownArray,
457
- ForwardAccumulator extends UnknownArray = [],
458
- BackwardAccumulator extends UnknownArray = [],
459
- > =
460
- TArray extends UnknownArray // For distributing `TArray`
461
- ? keyof TArray & `${number}` extends never
462
- // Enters this branch, if `TArray` is empty (e.g., []),
463
- // or `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
464
- ? TArray extends readonly [...infer Rest, infer Last]
465
- ? _CollapseRestElement<Rest, ForwardAccumulator, [Last, ...BackwardAccumulator]> // Accumulate elements that are present after the rest element.
466
- : TArray extends readonly []
467
- ? [...ForwardAccumulator, ...BackwardAccumulator]
468
- : [...ForwardAccumulator, TArray[number], ...BackwardAccumulator] // Add the rest element between the accumulated elements.
469
- : TArray extends readonly [(infer First)?, ...infer Rest]
470
- ? _CollapseRestElement<
471
- Rest,
472
- [
473
- ...ForwardAccumulator,
474
- '0' extends OptionalKeysOf<TArray>
475
- ? If<IsExactOptionalPropertyTypesEnabled, First, First | undefined> // Add `| undefined` for optional elements, if `exactOptionalPropertyTypes` is disabled.
476
- : First,
477
- ],
478
- BackwardAccumulator
479
- >
480
- : never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays.
481
- : never; // Should never happen
482
-
483
- type Numeric = number | bigint;
484
-
485
- type Zero = 0 | 0n;
486
-
487
- /**
488
- Matches the hidden `Infinity` type.
489
-
490
- Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
491
-
492
- @see NegativeInfinity
493
-
494
- @category Numeric
495
- */
496
- // See https://github.com/microsoft/TypeScript/issues/31752
497
- // eslint-disable-next-line no-loss-of-precision
498
- type PositiveInfinity = 1e999;
499
-
500
- /**
501
- Matches the hidden `-Infinity` type.
502
-
503
- Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
504
-
505
- @see PositiveInfinity
506
-
507
- @category Numeric
508
- */
509
- // See https://github.com/microsoft/TypeScript/issues/31752
510
- // eslint-disable-next-line no-loss-of-precision
511
- type NegativeInfinity = -1e999;
512
-
513
- /**
514
- A negative `number`/`bigint` (`-∞ < x < 0`)
515
-
516
- Use-case: Validating and documenting parameters.
517
-
518
- @see NegativeInteger
519
- @see NonNegative
520
-
521
- @category Numeric
522
- */
523
- type Negative<T extends Numeric> = T extends Zero ? never : `${T}` extends `-${string}` ? T : never;
524
-
525
- /**
526
- Returns a boolean for whether the given number is a negative number.
527
-
528
- @see Negative
529
-
530
- @example
531
- ```
532
- import type {IsNegative} from 'type-fest';
533
-
534
- type ShouldBeFalse = IsNegative<1>;
535
- type ShouldBeTrue = IsNegative<-1>;
536
- ```
537
-
538
- @category Numeric
539
- */
540
- type IsNegative<T extends Numeric> = T extends Negative<T> ? true : false;
541
-
542
- /**
543
- Returns a boolean for whether the two given types are equal.
544
-
545
- @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
546
- @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
547
-
548
- Use-cases:
549
- - If you want to make a conditional branch based on the result of a comparison of two types.
550
-
551
- @example
552
- ```
553
- import type {IsEqual} from 'type-fest';
554
-
555
- // This type returns a boolean for whether the given array includes the given item.
556
- // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
557
- type Includes<Value extends readonly any[], Item> =
558
- Value extends readonly [Value[0], ...infer rest]
559
- ? IsEqual<Value[0], Item> extends true
560
- ? true
561
- : Includes<rest, Item>
562
- : false;
563
- ```
564
-
565
- @category Type Guard
566
- @category Utilities
567
- */
568
- type IsEqual<A, B> =
569
- (<G>() => G extends A & G | G ? 1 : 2) extends
570
- (<G>() => G extends B & G | G ? 1 : 2)
571
- ? true
572
- : false;
573
-
574
- /**
575
- Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
576
-
577
- @example
578
- ```
579
- import type {Simplify} from 'type-fest';
580
-
581
- type PositionProps = {
582
- top: number;
583
- left: number;
584
- };
585
-
586
- type SizeProps = {
587
- width: number;
588
- height: number;
589
- };
590
-
591
- // In your editor, hovering over `Props` will show a flattened object with all the properties.
592
- type Props = Simplify<PositionProps & SizeProps>;
593
- ```
594
-
595
- Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.
596
-
597
- If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.
598
-
599
- @example
600
- ```
601
- import type {Simplify} from 'type-fest';
602
-
603
- interface SomeInterface {
604
- foo: number;
605
- bar?: string;
606
- baz: number | undefined;
607
- }
608
-
609
- type SomeType = {
610
- foo: number;
611
- bar?: string;
612
- baz: number | undefined;
613
- };
614
-
615
- const literal = {foo: 123, bar: 'hello', baz: 456};
616
- const someType: SomeType = literal;
617
- const someInterface: SomeInterface = literal;
618
-
619
- function fn(object: Record<string, unknown>): void {}
620
-
621
- fn(literal); // Good: literal object type is sealed
622
- fn(someType); // Good: type is sealed
623
- fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
624
- fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
625
- ```
626
-
627
- @link https://github.com/microsoft/TypeScript/issues/15300
628
- @see SimplifyDeep
629
- @category Object
630
- */
631
- type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
632
-
633
- /**
634
- Omit any index signatures from the given object type, leaving only explicitly defined properties.
635
-
636
- This is the counterpart of `PickIndexSignature`.
637
-
638
- Use-cases:
639
- - Remove overly permissive signatures from third-party types.
640
-
641
- This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
642
-
643
- It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
644
-
645
- (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
646
-
647
- ```
648
- const indexed: Record<string, unknown> = {}; // Allowed
649
-
650
- const keyed: Record<'foo', unknown> = {}; // Error
651
- // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
652
- ```
653
-
654
- Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another:
655
-
656
- ```
657
- type Indexed = {} extends Record<string, unknown>
658
- ? '✅ `{}` is assignable to `Record<string, unknown>`'
659
- : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
660
- // => '✅ `{}` is assignable to `Record<string, unknown>`'
661
-
662
- type Keyed = {} extends Record<'foo' | 'bar', unknown>
663
- ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
664
- : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
665
- // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
666
- ```
667
-
668
- Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`...
669
-
670
- ```
671
- import type {OmitIndexSignature} from 'type-fest';
672
-
673
- type OmitIndexSignature<ObjectType> = {
674
- [KeyType in keyof ObjectType // Map each key of `ObjectType`...
675
- ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
676
- };
677
- ```
678
-
679
- ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
680
-
681
- ```
682
- import type {OmitIndexSignature} from 'type-fest';
683
-
684
- type OmitIndexSignature<ObjectType> = {
685
- [KeyType in keyof ObjectType
686
- // Is `{}` assignable to `Record<KeyType, unknown>`?
687
- as {} extends Record<KeyType, unknown>
688
- ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
689
- : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
690
- ]: ObjectType[KeyType];
691
- };
692
- ```
693
-
694
- If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
695
-
696
- @example
697
- ```
698
- import type {OmitIndexSignature} from 'type-fest';
699
-
700
- interface Example {
701
- // These index signatures will be removed.
702
- [x: string]: any
703
- [x: number]: any
704
- [x: symbol]: any
705
- [x: `head-${string}`]: string
706
- [x: `${string}-tail`]: string
707
- [x: `head-${string}-tail`]: string
708
- [x: `${bigint}`]: string
709
- [x: `embedded-${number}`]: string
710
-
711
- // These explicitly defined keys will remain.
712
- foo: 'bar';
713
- qux?: 'baz';
714
- }
715
-
716
- type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
717
- // => { foo: 'bar'; qux?: 'baz' | undefined; }
718
- ```
719
-
720
- @see PickIndexSignature
721
- @category Object
722
- */
723
- type OmitIndexSignature<ObjectType> = {
724
- [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
725
- ? never
726
- : KeyType]: ObjectType[KeyType];
727
- };
728
-
729
- /**
730
- Pick only index signatures from the given object type, leaving out all explicitly defined properties.
731
-
732
- This is the counterpart of `OmitIndexSignature`.
733
-
734
- @example
735
- ```
736
- import type {PickIndexSignature} from 'type-fest';
737
-
738
- declare const symbolKey: unique symbol;
739
-
740
- type Example = {
741
- // These index signatures will remain.
742
- [x: string]: unknown;
743
- [x: number]: unknown;
744
- [x: symbol]: unknown;
745
- [x: `head-${string}`]: string;
746
- [x: `${string}-tail`]: string;
747
- [x: `head-${string}-tail`]: string;
748
- [x: `${bigint}`]: string;
749
- [x: `embedded-${number}`]: string;
750
-
751
- // These explicitly defined keys will be removed.
752
- ['kebab-case-key']: string;
753
- [symbolKey]: string;
754
- foo: 'bar';
755
- qux?: 'baz';
756
- };
757
-
758
- type ExampleIndexSignature = PickIndexSignature<Example>;
759
- // {
760
- // [x: string]: unknown;
761
- // [x: number]: unknown;
762
- // [x: symbol]: unknown;
763
- // [x: `head-${string}`]: string;
764
- // [x: `${string}-tail`]: string;
765
- // [x: `head-${string}-tail`]: string;
766
- // [x: `${bigint}`]: string;
767
- // [x: `embedded-${number}`]: string;
768
- // }
769
- ```
770
-
771
- @see OmitIndexSignature
772
- @category Object
773
- */
774
- type PickIndexSignature<ObjectType> = {
775
- [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
776
- ? KeyType
777
- : never]: ObjectType[KeyType];
778
- };
779
-
780
- // Merges two objects without worrying about index signatures.
781
- type SimpleMerge<Destination, Source> = {
782
- [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
783
- } & Source;
784
-
785
- /**
786
- Merge two types into a new type. Keys of the second type overrides keys of the first type.
787
-
788
- @example
789
- ```
790
- import type {Merge} from 'type-fest';
791
-
792
- interface Foo {
793
- [x: string]: unknown;
794
- [x: number]: unknown;
795
- foo: string;
796
- bar: symbol;
797
- }
798
-
799
- type Bar = {
800
- [x: number]: number;
801
- [x: symbol]: unknown;
802
- bar: Date;
803
- baz: boolean;
804
- };
805
-
806
- export type FooBar = Merge<Foo, Bar>;
807
- // => {
808
- // [x: string]: unknown;
809
- // [x: number]: number;
810
- // [x: symbol]: unknown;
811
- // foo: string;
812
- // bar: Date;
813
- // baz: boolean;
814
- // }
815
- ```
816
-
817
- @category Object
818
- */
819
- type Merge<Destination, Source> =
820
- Simplify<
821
- SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
822
- & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
823
- >;
824
-
825
- /**
826
- Merges user specified options with default options.
827
-
828
- @example
829
- ```
830
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
831
- type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
832
- type SpecifiedOptions = {leavesOnly: true};
833
-
834
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
835
- //=> {maxRecursionDepth: 10; leavesOnly: true}
836
- ```
837
-
838
- @example
839
- ```
840
- // Complains if default values are not provided for optional options
841
-
842
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
843
- type DefaultPathsOptions = {maxRecursionDepth: 10};
844
- type SpecifiedOptions = {};
845
-
846
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
847
- // ~~~~~~~~~~~~~~~~~~~
848
- // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
849
- ```
850
-
851
- @example
852
- ```
853
- // Complains if an option's default type does not conform to the expected type
854
-
855
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
856
- type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
857
- type SpecifiedOptions = {};
858
-
859
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
860
- // ~~~~~~~~~~~~~~~~~~~
861
- // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
862
- ```
863
-
864
- @example
865
- ```
866
- // Complains if an option's specified type does not conform to the expected type
867
-
868
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
869
- type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
870
- type SpecifiedOptions = {leavesOnly: 'yes'};
871
-
872
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
873
- // ~~~~~~~~~~~~~~~~
874
- // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
875
- ```
876
- */
877
- type ApplyDefaultOptions<
878
- Options extends object,
879
- Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
880
- SpecifiedOptions extends Options,
881
- > =
882
- If<IsAny<SpecifiedOptions>, Defaults,
883
- If<IsNever<SpecifiedOptions>, Defaults,
884
- Simplify<Merge<Defaults, {
885
- [Key in keyof SpecifiedOptions
886
- as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key
887
- ]: SpecifiedOptions[Key]
888
- }> & Required<Options>>>>;
889
-
890
- /**
891
- Returns a boolean for whether either of two given types are true.
892
-
893
- Use-case: Constructing complex conditional types where multiple conditions must be satisfied.
894
-
895
- @example
896
- ```
897
- import type {Or} from 'type-fest';
898
-
899
- type TT = Or<true, false>;
900
- //=> true
901
-
902
- type TF = Or<true, false>;
903
- //=> true
904
-
905
- type FT = Or<false, true>;
906
- //=> true
907
-
908
- type FF = Or<false, false>;
909
- //=> false
910
- ```
911
-
912
- Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
913
- For example, `And<false, boolean>` expands to `And<false, true> | And<false, false>`, which simplifies to `true | false` (i.e., `boolean`).
914
- @example
915
- ```
916
- import type {And} from 'type-fest';
917
-
918
- type A = Or<false, boolean>;
919
- //=> boolean
920
-
921
- type B = Or<boolean, false>;
922
- //=> boolean
923
-
924
- type C = Or<true, boolean>;
925
- //=> true
926
-
927
- type D = Or<boolean, true>;
928
- //=> true
929
-
930
- type E = Or<boolean, boolean>;
931
- //=> boolean
932
- ```
933
-
934
- Note: If `never` is passed as an argument, it is treated as `false` and the result is computed accordingly.
935
-
936
- @example
937
- ```
938
- import type {Or} from 'type-fest';
939
-
940
- type A = Or<true, never>;
941
- //=> true
942
-
943
- type B = Or<never, true>;
944
- //=> true
945
-
946
- type C = Or<false, never>;
947
- //=> false
948
-
949
- type D = Or<never, false>;
950
- //=> false
951
-
952
- type E = Or<boolean, never>;
953
- //=> boolean
954
-
955
- type F = Or<never, boolean>;
956
- //=> boolean
957
-
958
- type G = Or<never, never>;
959
- //=> false
960
- ```
961
-
962
- @see {@link And}
963
- */
964
- type Or<A extends boolean, B extends boolean> =
965
- _Or<If<IsNever<A>, false, A>, If<IsNever<B>, false, B>>; // `never` is treated as `false`
966
-
967
- type _Or<A extends boolean, B extends boolean> = A extends true
968
- ? true
969
- : B extends true
970
- ? true
971
- : false;
972
-
973
- /**
974
- @see {@link AllExtend}
975
- */
976
- type AllExtendOptions = {
977
- /**
978
- Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
979
-
980
- - When set to `true` (default), `never` is _not_ treated as a bottom type, instead, it is treated as a type that matches only itself (or `any`).
981
- - When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
982
-
983
- @default true
984
-
985
- @example
986
- ```
987
- import type {AllExtend} from 'type-fest';
988
-
989
- type A = AllExtend<[1, 2, never], number, {strictNever: true}>;
990
- //=> false
991
-
992
- type B = AllExtend<[1, 2, never], number, {strictNever: false}>;
993
- //=> true
994
-
995
- type C = AllExtend<[never, never], never, {strictNever: true}>;
996
- //=> true
997
-
998
- type D = AllExtend<[never, never], never, {strictNever: false}>;
999
- //=> true
1000
-
1001
- type E = AllExtend<['a', 'b', never], any, {strictNever: true}>;
1002
- //=> true
1003
-
1004
- type F = AllExtend<['a', 'b', never], any, {strictNever: false}>;
1005
- //=> true
1006
-
1007
- type G = AllExtend<[never, 1], never, {strictNever: true}>;
1008
- //=> false
1009
-
1010
- type H = AllExtend<[never, 1], never, {strictNever: false}>;
1011
- //=> false
1012
- ```
1013
- */
1014
- strictNever?: boolean;
1015
- };
1016
-
1017
- type DefaultAllExtendOptions = {
1018
- strictNever: true;
1019
- };
1020
-
1021
- /**
1022
- Returns a boolean for whether every element in an array type extends another type.
1023
-
1024
- @example
1025
- ```
1026
- import type {AllExtend} from 'type-fest';
1027
-
1028
- type A = AllExtend<[1, 2, 3], number>;
1029
- //=> true
1030
-
1031
- type B = AllExtend<[1, 2, '3'], number>;
1032
- //=> false
1033
-
1034
- type C = AllExtend<[number, number | string], number>;
1035
- //=> boolean
1036
-
1037
- type D = AllExtend<[true, boolean, true], true>;
1038
- //=> boolean
1039
- ```
1040
-
1041
- Note: Behaviour of optional elements depend on the `exactOptionalPropertyTypes` compiler option. When the option is disabled, the target type must include `undefined` for a successful match.
1042
-
1043
- ```
1044
- import type {AllExtend} from 'type-fest';
1045
-
1046
- // `exactOptionalPropertyTypes` enabled
1047
- type A = AllExtend<[1?, 2?, 3?], number>;
1048
- //=> true
1049
-
1050
- // `exactOptionalPropertyTypes` disabled
1051
- type B = AllExtend<[1?, 2?, 3?], number>;
1052
- //=> false
1053
-
1054
- // `exactOptionalPropertyTypes` disabled
1055
- type C = AllExtend<[1?, 2?, 3?], number | undefined>;
1056
- //=> true
1057
- ```
1058
-
1059
- @see {@link AllExtendOptions}
1060
-
1061
- @category Utilities
1062
- @category Array
1063
- */
1064
- type AllExtend<TArray extends UnknownArray, Type, Options extends AllExtendOptions = {}> =
1065
- _AllExtend<CollapseRestElement<TArray>, Type, ApplyDefaultOptions<AllExtendOptions, DefaultAllExtendOptions, Options>>;
1066
-
1067
- type _AllExtend<TArray extends UnknownArray, Type, Options extends Required<AllExtendOptions>> = IfNotAnyOrNever<TArray, If<IsAny<Type>, true,
1068
- TArray extends readonly [infer First, ...infer Rest]
1069
- ? IsNever<First> extends true
1070
- ? Or<IsNever<Type>, Not<Options['strictNever']>> extends true
1071
- // If target `Type` is also `never` OR `strictNever` is disabled, recurse further.
1072
- ? _AllExtend<Rest, Type, Options>
1073
- : false
1074
- : First extends Type
1075
- ? _AllExtend<Rest, Type, Options>
1076
- : false
1077
- : true
1078
- >, false, false>;
1079
-
1080
- /**
1081
- Returns a boolean for whether two given types are both true.
1082
-
1083
- Use-case: Constructing complex conditional types where multiple conditions must be satisfied.
1084
-
1085
- @example
1086
- ```
1087
- import type {And} from 'type-fest';
1088
-
1089
- type TT = And<true, true>;
1090
- //=> true
1091
-
1092
- type TF = And<true, false>;
1093
- //=> false
1094
-
1095
- type FT = And<false, true>;
1096
- //=> false
1097
-
1098
- type FF = And<false, false>;
1099
- //=> false
1100
- ```
1101
-
1102
- Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
1103
- For example, `And<true, boolean>` expands to `And<true, true> | And<true, false>`, which simplifies to `true | false` (i.e., `boolean`).
1104
-
1105
- @example
1106
- ```
1107
- import type {And} from 'type-fest';
1108
-
1109
- type A = And<true, boolean>;
1110
- //=> boolean
1111
-
1112
- type B = And<boolean, true>;
1113
- //=> boolean
1114
-
1115
- type C = And<false, boolean>;
1116
- //=> false
1117
-
1118
- type D = And<boolean, false>;
1119
- //=> false
1120
-
1121
- type E = And<boolean, boolean>;
1122
- //=> boolean
1123
- ```
1124
-
1125
- Note: If either of the types is `never`, the result becomes `false`.
1126
- @example
1127
- ```
1128
- import type {And} from 'type-fest';
1129
-
1130
- type A = And<true, never>;
1131
- //=> false
1132
-
1133
- type B = And<never, true>;
1134
- //=> false
1135
-
1136
- type C = And<false, never>;
1137
- //=> false
1138
-
1139
- type D = And<never, false>;
1140
- //=> false
1141
-
1142
- type E = And<boolean, never>;
1143
- //=> false
1144
-
1145
- type F = And<never, boolean>;
1146
- //=> false
1147
-
1148
- type G = And<never, never>;
1149
- //=> false
1150
- ```
1151
-
1152
- @see {@link Or}
1153
- */
1154
- type And<A extends boolean, B extends boolean> = AllExtend<[A, B], true>;
1155
-
1156
- /**
1157
- Returns a boolean for whether a given number is greater than another number.
1158
-
1159
- @example
1160
- ```
1161
- import type {GreaterThan} from 'type-fest';
1162
-
1163
- GreaterThan<1, -5>;
1164
- //=> true
1165
-
1166
- GreaterThan<1, 1>;
1167
- //=> false
1168
-
1169
- GreaterThan<1, 5>;
1170
- //=> false
1171
- ```
1172
- */
1173
- type GreaterThan<A extends number, B extends number> =
1174
- A extends number // For distributing `A`
1175
- ? B extends number // For distributing `B`
1176
- ? number extends A | B
1177
- ? never
1178
- : [
1179
- IsEqual<A, PositiveInfinity>, IsEqual<A, NegativeInfinity>,
1180
- IsEqual<B, PositiveInfinity>, IsEqual<B, NegativeInfinity>,
1181
- ] extends infer R extends [boolean, boolean, boolean, boolean]
1182
- ? Or<
1183
- And<IsEqual<R[0], true>, IsEqual<R[2], false>>,
1184
- And<IsEqual<R[3], true>, IsEqual<R[1], false>>
1185
- > extends true
1186
- ? true
1187
- : Or<
1188
- And<IsEqual<R[1], true>, IsEqual<R[3], false>>,
1189
- And<IsEqual<R[2], true>, IsEqual<R[0], false>>
1190
- > extends true
1191
- ? false
1192
- : true extends R[number]
1193
- ? false
1194
- : [IsNegative<A>, IsNegative<B>] extends infer R extends [boolean, boolean]
1195
- ? [true, false] extends R
1196
- ? false
1197
- : [false, true] extends R
1198
- ? true
1199
- : [false, false] extends R
1200
- ? PositiveNumericStringGt<`${A}`, `${B}`>
1201
- : PositiveNumericStringGt<`${NumberAbsolute<B>}`, `${NumberAbsolute<A>}`>
1202
- : never
1203
- : never
1204
- : never // Should never happen
1205
- : never; // Should never happen
1206
-
1207
- /**
1208
- Returns a boolean for whether a given number is greater than or equal to another number.
1209
-
1210
- @example
1211
- ```
1212
- import type {GreaterThanOrEqual} from 'type-fest';
1213
-
1214
- GreaterThanOrEqual<1, -5>;
1215
- //=> true
1216
-
1217
- GreaterThanOrEqual<1, 1>;
1218
- //=> true
1219
-
1220
- GreaterThanOrEqual<1, 5>;
1221
- //=> false
1222
- ```
1223
- */
1224
- type GreaterThanOrEqual<A extends number, B extends number> = number extends A | B
1225
- ? never
1226
- : A extends B ? true : GreaterThan<A, B>;
1227
-
1228
- /**
1229
- Returns a boolean for whether a given number is less than another number.
1230
-
1231
- @example
1232
- ```
1233
- import type {LessThan} from 'type-fest';
1234
-
1235
- LessThan<1, -5>;
1236
- //=> false
1237
-
1238
- LessThan<1, 1>;
1239
- //=> false
1240
-
1241
- LessThan<1, 5>;
1242
- //=> true
1243
- ```
1244
- */
1245
- type LessThan<A extends number, B extends number> = number extends A | B
1246
- ? never
1247
- : GreaterThanOrEqual<A, B> extends infer Result
1248
- ? Result extends true
1249
- ? false
1250
- : true
1251
- : never; // Should never happen
1252
-
1253
- // Should never happen
1254
-
1255
- /**
1256
- Create a tuple type of the given length `<L>` and fill it with the given type `<Fill>`.
1257
-
1258
- If `<Fill>` is not provided, it will default to `unknown`.
1259
-
1260
- @link https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f
1261
- */
1262
- type BuildTuple<L extends number, Fill = unknown, T extends readonly unknown[] = []> = number extends L
1263
- ? Fill[]
1264
- : L extends T['length']
1265
- ? T
1266
- : BuildTuple<L, Fill, [...T, Fill]>;
1267
-
1268
- /**
1269
- Return a string representation of the given string or number.
1270
-
1271
- Note: This type is not the return type of the `.toString()` function.
1272
- */
1273
- type ToString<T> = T extends string | number ? `${T}` : never;
1274
-
1275
- /**
1276
- Converts a numeric string to a number.
1277
-
1278
- @example
1279
- ```
1280
- type PositiveInt = StringToNumber<'1234'>;
1281
- //=> 1234
1282
-
1283
- type NegativeInt = StringToNumber<'-1234'>;
1284
- //=> -1234
1285
-
1286
- type PositiveFloat = StringToNumber<'1234.56'>;
1287
- //=> 1234.56
1288
-
1289
- type NegativeFloat = StringToNumber<'-1234.56'>;
1290
- //=> -1234.56
1291
-
1292
- type PositiveInfinity = StringToNumber<'Infinity'>;
1293
- //=> Infinity
1294
-
1295
- type NegativeInfinity = StringToNumber<'-Infinity'>;
1296
- //=> -Infinity
1297
- ```
1298
-
1299
- @category String
1300
- @category Numeric
1301
- @category Template literal
1302
- */
1303
- type StringToNumber<S extends string> = S extends `${infer N extends number}`
1304
- ? N
1305
- : S extends 'Infinity'
1306
- ? PositiveInfinity
1307
- : S extends '-Infinity'
1308
- ? NegativeInfinity
1309
- : never;
1310
-
1311
- /**
1312
- Returns an array of the characters of the string.
1313
-
1314
- @example
1315
- ```
1316
- StringToArray<'abcde'>;
1317
- //=> ['a', 'b', 'c', 'd', 'e']
1318
-
1319
- StringToArray<string>;
1320
- //=> never
1321
- ```
1322
-
1323
- @category String
1324
- */
1325
- type StringToArray<S extends string, Result extends string[] = []> = string extends S
1326
- ? never
1327
- : S extends `${infer F}${infer R}`
1328
- ? StringToArray<R, [...Result, F]>
1329
- : Result;
1330
-
1331
- /**
1332
- Returns the length of the given string.
1333
-
1334
- @example
1335
- ```
1336
- StringLength<'abcde'>;
1337
- //=> 5
1338
-
1339
- StringLength<string>;
1340
- //=> never
1341
- ```
1342
-
1343
- @category String
1344
- @category Template literal
1345
- */
1346
- type StringLength<S extends string> = string extends S
1347
- ? never
1348
- : StringToArray<S>['length'];
1349
-
1350
- /**
1351
- Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both numeric strings and have the same length.
1352
-
1353
- @example
1354
- ```
1355
- SameLengthPositiveNumericStringGt<'50', '10'>;
1356
- //=> true
1357
-
1358
- SameLengthPositiveNumericStringGt<'10', '10'>;
1359
- //=> false
1360
- ```
1361
- */
1362
- type SameLengthPositiveNumericStringGt<A extends string, B extends string> = A extends `${infer FirstA}${infer RestA}`
1363
- ? B extends `${infer FirstB}${infer RestB}`
1364
- ? FirstA extends FirstB
1365
- ? SameLengthPositiveNumericStringGt<RestA, RestB>
1366
- : PositiveNumericCharacterGt<FirstA, FirstB>
1367
- : never
1368
- : false;
1369
-
1370
- type NumericString = '0123456789';
1371
-
1372
- /**
1373
- Returns a boolean for whether `A` is greater than `B`, where `A` and `B` are both positive numeric strings.
1374
-
1375
- @example
1376
- ```
1377
- PositiveNumericStringGt<'500', '1'>;
1378
- //=> true
1379
-
1380
- PositiveNumericStringGt<'1', '1'>;
1381
- //=> false
1382
-
1383
- PositiveNumericStringGt<'1', '500'>;
1384
- //=> false
1385
- ```
1386
- */
1387
- type PositiveNumericStringGt<A extends string, B extends string> = A extends B
1388
- ? false
1389
- : [BuildTuple<StringLength<A>, 0>, BuildTuple<StringLength<B>, 0>] extends infer R extends [readonly unknown[], readonly unknown[]]
1390
- ? R[0] extends [...R[1], ...infer Remain extends readonly unknown[]]
1391
- ? 0 extends Remain['length']
1392
- ? SameLengthPositiveNumericStringGt<A, B>
1393
- : true
1394
- : false
1395
- : never;
1396
-
1397
- /**
1398
- Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both positive numeric characters.
1399
-
1400
- @example
1401
- ```
1402
- PositiveNumericCharacterGt<'5', '1'>;
1403
- //=> true
1404
-
1405
- PositiveNumericCharacterGt<'1', '1'>;
1406
- //=> false
1407
- ```
1408
- */
1409
- type PositiveNumericCharacterGt<A extends string, B extends string> = NumericString extends `${infer HeadA}${A}${infer TailA}`
1410
- ? NumericString extends `${infer HeadB}${B}${infer TailB}`
1411
- ? HeadA extends `${HeadB}${infer _}${infer __}`
1412
- ? true
1413
- : false
1414
- : never
1415
- : never;
1416
-
1417
- /**
1418
- Returns the absolute value of a given value.
1419
-
1420
- @example
1421
- ```
1422
- NumberAbsolute<-1>;
1423
- //=> 1
1424
-
1425
- NumberAbsolute<1>;
1426
- //=> 1
1427
-
1428
- NumberAbsolute<NegativeInfinity>
1429
- //=> PositiveInfinity
1430
- ```
1431
- */
1432
- type NumberAbsolute<N extends number> = `${N}` extends `-${infer StringPositiveN}` ? StringToNumber<StringPositiveN> : N;
1433
-
1434
- /**
1435
- Check whether the given type is a number or a number string.
1436
-
1437
- Supports floating-point as a string.
1438
-
1439
- @example
1440
- ```
1441
- type A = IsNumberLike<'1'>;
1442
- //=> true
1443
-
1444
- type B = IsNumberLike<'-1.1'>;
1445
- //=> true
1446
-
1447
- type C = IsNumberLike<'5e-20'>;
1448
- //=> true
1449
-
1450
- type D = IsNumberLike<1>;
1451
- //=> true
1452
-
1453
- type E = IsNumberLike<'a'>;
1454
- //=> false
1455
- */
1456
- type IsNumberLike<N> =
1457
- IsAnyOrNever<N> extends true ? N
1458
- : N extends number | `${number}`
1459
- ? true
1460
- : false;
1461
-
1462
- /**
1463
- Returns the number with reversed sign.
1464
-
1465
- @example
1466
- ```
1467
- ReverseSign<-1>;
1468
- //=> 1
1469
-
1470
- ReverseSign<1>;
1471
- //=> -1
1472
-
1473
- ReverseSign<NegativeInfinity>
1474
- //=> PositiveInfinity
1475
-
1476
- ReverseSign<PositiveInfinity>
1477
- //=> NegativeInfinity
1478
- ```
1479
- */
1480
- type ReverseSign<N extends number> =
1481
- // Handle edge cases
1482
- N extends 0 ? 0 : N extends PositiveInfinity ? NegativeInfinity : N extends NegativeInfinity ? PositiveInfinity :
1483
- // Handle negative numbers
1484
- `${N}` extends `-${infer P extends number}` ? P
1485
- // Handle positive numbers
1486
- : `-${N}` extends `${infer R extends number}` ? R : never;
1487
-
1488
- /**
1489
- Returns the difference between two numbers.
1490
-
1491
- Note:
1492
- - A or B can only support `-999` ~ `999`.
1493
-
1494
- @example
1495
- ```
1496
- import type {Subtract} from 'type-fest';
1497
-
1498
- Subtract<333, 222>;
1499
- //=> 111
1500
-
1501
- Subtract<111, -222>;
1502
- //=> 333
1503
-
1504
- Subtract<-111, 222>;
1505
- //=> -333
1506
-
1507
- Subtract<18, 96>;
1508
- //=> -78
1509
-
1510
- Subtract<PositiveInfinity, 9999>;
1511
- //=> PositiveInfinity
1512
-
1513
- Subtract<PositiveInfinity, PositiveInfinity>;
1514
- //=> number
1515
- ```
1516
-
1517
- @category Numeric
1518
- */
1519
- // TODO: Support big integer.
1520
- type Subtract<A extends number, B extends number> =
1521
- // Handle cases when A or B is the actual "number" type
1522
- number extends A | B ? number
1523
- // Handle cases when A and B are both +/- infinity
1524
- : A extends B & (PositiveInfinity | NegativeInfinity) ? number
1525
- // Handle cases when A is - infinity or B is + infinity
1526
- : A extends NegativeInfinity ? NegativeInfinity : B extends PositiveInfinity ? NegativeInfinity
1527
- // Handle cases when A is + infinity or B is - infinity
1528
- : A extends PositiveInfinity ? PositiveInfinity : B extends NegativeInfinity ? PositiveInfinity
1529
- // Handle case when numbers are equal to each other
1530
- : A extends B ? 0
1531
- // Handle cases when A or B is 0
1532
- : A extends 0 ? ReverseSign<B> : B extends 0 ? A
1533
- // Handle remaining regular cases
1534
- : SubtractPostChecks<A, B>;
1535
-
1536
- /**
1537
- Subtracts two numbers A and B, such that they are not equal and neither of them are 0, +/- infinity or the `number` type
1538
- */
1539
- type SubtractPostChecks<A extends number, B extends number, AreNegative = [IsNegative<A>, IsNegative<B>]> =
1540
- AreNegative extends [false, false]
1541
- ? SubtractPositives<A, B>
1542
- : AreNegative extends [true, true]
1543
- // When both numbers are negative we subtract the absolute values and then reverse the sign
1544
- ? ReverseSign<SubtractPositives<NumberAbsolute<A>, NumberAbsolute<B>>>
1545
- // When the signs are different we can add the absolute values and then reverse the sign if A < B
1546
- : [...BuildTuple<NumberAbsolute<A>>, ...BuildTuple<NumberAbsolute<B>>] extends infer R extends unknown[]
1547
- ? LessThan<A, B> extends true ? ReverseSign<R['length']> : R['length']
1548
- : never;
1549
-
1550
- /**
1551
- Subtracts two positive numbers.
1552
- */
1553
- type SubtractPositives<A extends number, B extends number> =
1554
- LessThan<A, B> extends true
1555
- // When A < B we can reverse the result of B - A
1556
- ? ReverseSign<SubtractIfAGreaterThanB<B, A>>
1557
- : SubtractIfAGreaterThanB<A, B>;
1558
-
1559
- /**
1560
- Subtracts two positive numbers A and B such that A > B.
1561
- */
1562
- type SubtractIfAGreaterThanB<A extends number, B extends number> =
1563
- // This is where we always want to end up and do the actual subtraction
1564
- BuildTuple<A> extends [...BuildTuple<B>, ...infer R]
1565
- ? R['length']
1566
- : never;
1567
-
1568
- /**
1569
- Paths options.
1570
-
1571
- @see {@link Paths}
1572
- */
1573
- type PathsOptions = {
1574
- /**
1575
- The maximum depth to recurse when searching for paths. Range: 0 ~ 10.
1576
-
1577
- @default 5
1578
- */
1579
- maxRecursionDepth?: number;
1580
-
1581
- /**
1582
- Use bracket notation for array indices and numeric object keys.
1583
-
1584
- @default false
1585
-
1586
- @example
1587
- ```
1588
- type ArrayExample = {
1589
- array: ['foo'];
1590
- };
1591
-
1592
- type A = Paths<ArrayExample, {bracketNotation: false}>;
1593
- //=> 'array' | 'array.0'
1594
-
1595
- type B = Paths<ArrayExample, {bracketNotation: true}>;
1596
- //=> 'array' | 'array[0]'
1597
- ```
1598
-
1599
- @example
1600
- ```
1601
- type NumberKeyExample = {
1602
- 1: ['foo'];
1603
- };
1604
-
1605
- type A = Paths<NumberKeyExample, {bracketNotation: false}>;
1606
- //=> 1 | '1' | '1.0'
1607
-
1608
- type B = Paths<NumberKeyExample, {bracketNotation: true}>;
1609
- //=> '[1]' | '[1][0]'
1610
- ```
1611
- */
1612
- bracketNotation?: boolean;
1613
-
1614
- /**
1615
- Only include leaf paths in the output.
1616
-
1617
- @default false
1618
-
1619
- @example
1620
- ```
1621
- type Post = {
1622
- id: number;
1623
- author: {
1624
- id: number;
1625
- name: {
1626
- first: string;
1627
- last: string;
1628
- };
1629
- };
1630
- };
1631
-
1632
- type AllPaths = Paths<Post, {leavesOnly: false}>;
1633
- //=> 'id' | 'author' | 'author.id' | 'author.name' | 'author.name.first' | 'author.name.last'
1634
-
1635
- type LeafPaths = Paths<Post, {leavesOnly: true}>;
1636
- //=> 'id' | 'author.id' | 'author.name.first' | 'author.name.last'
1637
- ```
1638
-
1639
- @example
1640
- ```
1641
- type ArrayExample = {
1642
- array: Array<{foo: string}>;
1643
- tuple: [string, {bar: string}];
1644
- };
1645
-
1646
- type AllPaths = Paths<ArrayExample, {leavesOnly: false}>;
1647
- //=> 'array' | `array.${number}` | `array.${number}.foo` | 'tuple' | 'tuple.0' | 'tuple.1' | 'tuple.1.bar'
1648
-
1649
- type LeafPaths = Paths<ArrayExample, {leavesOnly: true}>;
1650
- //=> `array.${number}.foo` | 'tuple.0' | 'tuple.1.bar'
1651
- ```
1652
- */
1653
- leavesOnly?: boolean;
1654
-
1655
- /**
1656
- Only include paths at the specified depth. By default all paths up to {@link PathsOptions.maxRecursionDepth | `maxRecursionDepth`} are included.
1657
-
1658
- Note: Depth starts at `0` for root properties.
1659
-
1660
- @default number
1661
-
1662
- @example
1663
- ```
1664
- type Post = {
1665
- id: number;
1666
- author: {
1667
- id: number;
1668
- name: {
1669
- first: string;
1670
- last: string;
1671
- };
1672
- };
1673
- };
1674
-
1675
- type DepthZero = Paths<Post, {depth: 0}>;
1676
- //=> 'id' | 'author'
1677
-
1678
- type DepthOne = Paths<Post, {depth: 1}>;
1679
- //=> 'author.id' | 'author.name'
1680
-
1681
- type DepthTwo = Paths<Post, {depth: 2}>;
1682
- //=> 'author.name.first' | 'author.name.last'
1683
-
1684
- type LeavesAtDepthOne = Paths<Post, {leavesOnly: true; depth: 1}>;
1685
- //=> 'author.id'
1686
- ```
1687
- */
1688
- depth?: number;
1689
- };
1690
-
1691
- type DefaultPathsOptions = {
1692
- maxRecursionDepth: 5;
1693
- bracketNotation: false;
1694
- leavesOnly: false;
1695
- depth: number;
1696
- };
1697
-
1698
- /**
1699
- Generate a union of all possible paths to properties in the given object.
1700
-
1701
- It also works with arrays.
1702
-
1703
- Use-case: You want a type-safe way to access deeply nested properties in an object.
1704
-
1705
- @example
1706
- ```
1707
- import type {Paths} from 'type-fest';
1708
-
1709
- type Project = {
1710
- filename: string;
1711
- listA: string[];
1712
- listB: [{filename: string}];
1713
- folder: {
1714
- subfolder: {
1715
- filename: string;
1716
- };
1717
- };
1718
- };
1719
-
1720
- type ProjectPaths = Paths<Project>;
1721
- //=> 'filename' | 'listA' | 'listB' | 'folder' | `listA.${number}` | 'listB.0' | 'listB.0.filename' | 'folder.subfolder' | 'folder.subfolder.filename'
1722
-
1723
- declare function open<Path extends ProjectPaths>(path: Path): void;
1724
-
1725
- open('filename'); // Pass
1726
- open('folder.subfolder'); // Pass
1727
- open('folder.subfolder.filename'); // Pass
1728
- open('foo'); // TypeError
1729
-
1730
- // Also works with arrays
1731
- open('listA.1'); // Pass
1732
- open('listB.0'); // Pass
1733
- open('listB.1'); // TypeError. Because listB only has one element.
1734
- ```
1735
-
1736
- @category Object
1737
- @category Array
1738
- */
1739
- type Paths<T, Options extends PathsOptions = {}> = _Paths<T, ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, Options>>;
1740
-
1741
- type _Paths<T, Options extends Required<PathsOptions>> =
1742
- T extends NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>
1743
- ? never
1744
- : IsAny<T> extends true
1745
- ? never
1746
- : T extends UnknownArray
1747
- ? number extends T['length']
1748
- // We need to handle the fixed and non-fixed index part of the array separately.
1749
- ? InternalPaths<StaticPartOfArray<T>, Options> | InternalPaths<Array<VariablePartOfArray<T>[number]>, Options>
1750
- : InternalPaths<T, Options>
1751
- : T extends object
1752
- ? InternalPaths<T, Options>
1753
- : never;
1754
-
1755
- type InternalPaths<T, Options extends Required<PathsOptions>> =
1756
- Options['maxRecursionDepth'] extends infer MaxDepth extends number
1757
- ? Required<T> extends infer T
1758
- ? T extends readonly []
1759
- ? never
1760
- : IsNever<keyof T> extends true // Check for empty object
1761
- ? never
1762
- : {
1763
- [Key in keyof T]:
1764
- Key extends string | number // Limit `Key` to string or number.
1765
- ? (
1766
- Options['bracketNotation'] extends true
1767
- ? IsNumberLike<Key> extends true
1768
- ? `[${Key}]`
1769
- : (Key | ToString<Key>)
1770
- : Options['bracketNotation'] extends false
1771
- // If `Key` is a number, return `Key | `${Key}``, because both `array[0]` and `array['0']` work.
1772
- ? (Key | ToString<Key>)
1773
- : never
1774
- ) extends infer TranformedKey extends string | number ?
1775
- // 1. If style is 'a[0].b' and 'Key' is a numberlike value like 3 or '3', transform 'Key' to `[${Key}]`, else to `${Key}` | Key
1776
- // 2. If style is 'a.0.b', transform 'Key' to `${Key}` | Key
1777
- | ((Options['leavesOnly'] extends true
1778
- ? MaxDepth extends 0
1779
- ? TranformedKey
1780
- : T[Key] extends infer Value
1781
- ? (Value extends readonly [] | NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>
1782
- ? TranformedKey
1783
- : IsNever<keyof Value> extends true // Check for empty object
1784
- ? TranformedKey
1785
- : never)
1786
- : never
1787
- : TranformedKey
1788
- ) extends infer _TransformedKey
1789
- // If `depth` is provided, the condition becomes truthy only when it reaches `0`.
1790
- // Otherwise, since `depth` defaults to `number`, the condition is always truthy, returning paths at all depths.
1791
- ? 0 extends Options['depth']
1792
- ? _TransformedKey
1793
- : never
1794
- : never)
1795
- | (
1796
- // Recursively generate paths for the current key
1797
- GreaterThan<MaxDepth, 0> extends true // Limit the depth to prevent infinite recursion
1798
- ? _Paths<T[Key],
1799
- {
1800
- bracketNotation: Options['bracketNotation'];
1801
- maxRecursionDepth: Subtract<MaxDepth, 1>;
1802
- leavesOnly: Options['leavesOnly'];
1803
- depth: Subtract<Options['depth'], 1>;
1804
- }> extends infer SubPath
1805
- ? SubPath extends string | number
1806
- ? (
1807
- Options['bracketNotation'] extends true
1808
- ? SubPath extends `[${any}]` | `[${any}]${string}`
1809
- ? `${TranformedKey}${SubPath}` // If next node is number key like `[3]`, no need to add `.` before it.
1810
- : `${TranformedKey}.${SubPath}`
1811
- : never
1812
- ) | (
1813
- Options['bracketNotation'] extends false
1814
- ? `${TranformedKey}.${SubPath}`
1815
- : never
1816
- )
1817
- : never
1818
- : never
1819
- : never
1820
- )
1821
- : never
1822
- : never
1823
- }[keyof T & (T extends UnknownArray ? number : unknown)]
1824
- : never
1825
- : never;
1826
-
1827
- /**
1828
- Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.
1829
-
1830
- Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals.
1831
-
1832
- This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore.
1833
-
1834
- @example
1835
- ```
1836
- import type {LiteralUnion} from 'type-fest';
1837
-
1838
- // Before
1839
-
1840
- type Pet = 'dog' | 'cat' | string;
1841
-
1842
- const pet: Pet = '';
1843
- // Start typing in your TypeScript-enabled IDE.
1844
- // You **will not** get auto-completion for `dog` and `cat` literals.
1845
-
1846
- // After
1847
-
1848
- type Pet2 = LiteralUnion<'dog' | 'cat', string>;
1849
-
1850
- const pet: Pet2 = '';
1851
- // You **will** get auto-completion for `dog` and `cat` literals.
1852
- ```
1853
-
1854
- @category Type
1855
- */
1856
- type LiteralUnion<
1857
- LiteralType,
1858
- BaseType extends Primitive,
1859
- > = LiteralType | (BaseType & Record<never, never>);
1860
-
1861
- declare namespace PackageJson$1 {
1862
- /**
1863
- A person who has been involved in creating or maintaining the package.
1864
- */
1865
- export type Person =
1866
- | string
1867
- | {
1868
- name: string;
1869
- url?: string;
1870
- email?: string;
1871
- };
1872
-
1873
- export type BugsLocation =
1874
- | string
1875
- | {
1876
- /**
1877
- The URL to the package's issue tracker.
1878
- */
1879
- url?: string;
1880
-
1881
- /**
1882
- The email address to which issues should be reported.
1883
- */
1884
- email?: string;
1885
- };
1886
-
1887
- export type DirectoryLocations = {
1888
- [directoryType: string]: JsonValue | undefined;
1889
-
1890
- /**
1891
- Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder.
1892
- */
1893
- bin?: string;
1894
-
1895
- /**
1896
- Location for Markdown files.
1897
- */
1898
- doc?: string;
1899
-
1900
- /**
1901
- Location for example scripts.
1902
- */
1903
- example?: string;
1904
-
1905
- /**
1906
- Location for the bulk of the library.
1907
- */
1908
- lib?: string;
1909
-
1910
- /**
1911
- Location for man pages. Sugar to generate a `man` array by walking the folder.
1912
- */
1913
- man?: string;
1914
-
1915
- /**
1916
- Location for test files.
1917
- */
1918
- test?: string;
1919
- };
1920
-
1921
- export type Scripts = {
1922
- /**
1923
- Run **before** the package is published (Also run on local `npm install` without any arguments).
1924
- */
1925
- prepublish?: string;
1926
-
1927
- /**
1928
- Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`.
1929
- */
1930
- prepare?: string;
1931
-
1932
- /**
1933
- Run **before** the package is prepared and packed, **only** on `npm publish`.
1934
- */
1935
- prepublishOnly?: string;
1936
-
1937
- /**
1938
- Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies).
1939
- */
1940
- prepack?: string;
1941
-
1942
- /**
1943
- Run **after** the tarball has been generated and moved to its final destination.
1944
- */
1945
- postpack?: string;
1946
-
1947
- /**
1948
- Run **after** the package is published.
1949
- */
1950
- publish?: string;
1951
-
1952
- /**
1953
- Run **after** the package is published.
1954
- */
1955
- postpublish?: string;
1956
-
1957
- /**
1958
- Run **before** the package is installed.
1959
- */
1960
- preinstall?: string;
1961
-
1962
- /**
1963
- Run **after** the package is installed.
1964
- */
1965
- install?: string;
1966
-
1967
- /**
1968
- Run **after** the package is installed and after `install`.
1969
- */
1970
- postinstall?: string;
1971
-
1972
- /**
1973
- Run **before** the package is uninstalled and before `uninstall`.
1974
- */
1975
- preuninstall?: string;
1976
-
1977
- /**
1978
- Run **before** the package is uninstalled.
1979
- */
1980
- uninstall?: string;
1981
-
1982
- /**
1983
- Run **after** the package is uninstalled.
1984
- */
1985
- postuninstall?: string;
1986
-
1987
- /**
1988
- Run **before** bump the package version and before `version`.
1989
- */
1990
- preversion?: string;
1991
-
1992
- /**
1993
- Run **before** bump the package version.
1994
- */
1995
- version?: string;
1996
-
1997
- /**
1998
- Run **after** bump the package version.
1999
- */
2000
- postversion?: string;
2001
-
2002
- /**
2003
- Run with the `npm test` command, before `test`.
2004
- */
2005
- pretest?: string;
2006
-
2007
- /**
2008
- Run with the `npm test` command.
2009
- */
2010
- test?: string;
2011
-
2012
- /**
2013
- Run with the `npm test` command, after `test`.
2014
- */
2015
- posttest?: string;
2016
-
2017
- /**
2018
- Run with the `npm stop` command, before `stop`.
2019
- */
2020
- prestop?: string;
2021
-
2022
- /**
2023
- Run with the `npm stop` command.
2024
- */
2025
- stop?: string;
2026
-
2027
- /**
2028
- Run with the `npm stop` command, after `stop`.
2029
- */
2030
- poststop?: string;
2031
-
2032
- /**
2033
- Run with the `npm start` command, before `start`.
2034
- */
2035
- prestart?: string;
2036
-
2037
- /**
2038
- Run with the `npm start` command.
2039
- */
2040
- start?: string;
2041
-
2042
- /**
2043
- Run with the `npm start` command, after `start`.
2044
- */
2045
- poststart?: string;
2046
-
2047
- /**
2048
- Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
2049
- */
2050
- prerestart?: string;
2051
-
2052
- /**
2053
- Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
2054
- */
2055
- restart?: string;
2056
-
2057
- /**
2058
- Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
2059
- */
2060
- postrestart?: string;
2061
- } & Partial<Record<string, string>>;
2062
-
2063
- /**
2064
- Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL.
2065
- */
2066
- export type Dependency = Partial<Record<string, string>>;
2067
-
2068
- /**
2069
- A mapping of conditions and the paths to which they resolve.
2070
- */
2071
- type ExportConditions = {
2072
- [condition: string]: Exports;
2073
- };
2074
-
2075
- /**
2076
- Entry points of a module, optionally with conditions and subpath exports.
2077
- */
2078
- export type Exports =
2079
- | null
2080
- | string
2081
- | Array<string | ExportConditions>
2082
- | ExportConditions;
2083
-
2084
- /**
2085
- Import map entries of a module, optionally with conditions and subpath imports.
2086
- */
2087
- export type Imports = {
2088
- [key: `#${string}`]: Exports;
2089
- };
2090
-
2091
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
2092
- export interface NonStandardEntryPoints {
2093
- /**
2094
- An ECMAScript module ID that is the primary entry point to the program.
2095
- */
2096
- module?: string;
2097
-
2098
- /**
2099
- A module ID with untranspiled code that is the primary entry point to the program.
2100
- */
2101
- esnext?:
2102
- | string
2103
- | {
2104
- [moduleName: string]: string | undefined;
2105
- main?: string;
2106
- browser?: string;
2107
- };
2108
-
2109
- /**
2110
- A hint to JavaScript bundlers or component tools when packaging modules for client side use.
2111
- */
2112
- browser?:
2113
- | string
2114
- | Partial<Record<string, string | false>>;
2115
-
2116
- /**
2117
- Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused.
2118
-
2119
- [Read more.](https://webpack.js.org/guides/tree-shaking/)
2120
- */
2121
- sideEffects?: boolean | string[];
2122
- }
2123
-
2124
- export type TypeScriptConfiguration = {
2125
- /**
2126
- Location of the bundled TypeScript declaration file.
2127
- */
2128
- types?: string;
2129
-
2130
- /**
2131
- Version selection map of TypeScript.
2132
- */
2133
- typesVersions?: Partial<Record<string, Partial<Record<string, string[]>>>>;
2134
-
2135
- /**
2136
- Location of the bundled TypeScript declaration file. Alias of `types`.
2137
- */
2138
- typings?: string;
2139
- };
2140
-
2141
- /**
2142
- An alternative configuration for workspaces.
2143
- */
2144
- export type WorkspaceConfig = {
2145
- /**
2146
- An array of workspace pattern strings which contain the workspace packages.
2147
- */
2148
- packages?: WorkspacePattern[];
2149
-
2150
- /**
2151
- Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns.
2152
-
2153
- [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn.
2154
- [Not supported](https://github.com/npm/rfcs/issues/287) by npm.
2155
- */
2156
- nohoist?: WorkspacePattern[];
2157
- };
2158
-
2159
- /**
2160
- A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process.
2161
-
2162
- The patterns are handled with [minimatch](https://github.com/isaacs/minimatch).
2163
-
2164
- @example
2165
- `docs` → Include the docs directory and install its dependencies.
2166
- `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`.
2167
- */
2168
- type WorkspacePattern = string;
2169
-
2170
- export type YarnConfiguration = {
2171
- /**
2172
- If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`.
2173
-
2174
- Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line.
2175
- */
2176
- flat?: boolean;
2177
-
2178
- /**
2179
- Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file.
2180
- */
2181
- resolutions?: Dependency;
2182
- };
2183
-
2184
- export type JSPMConfiguration = {
2185
- /**
2186
- JSPM configuration.
2187
- */
2188
- jspm?: PackageJson$1;
2189
- };
2190
-
2191
- /**
2192
- Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties.
2193
- */
2194
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
2195
- export interface PackageJsonStandard {
2196
- /**
2197
- The name of the package.
2198
- */
2199
- name?: string;
2200
-
2201
- /**
2202
- Package version, parseable by [`node-semver`](https://github.com/npm/node-semver).
2203
- */
2204
- version?: string;
2205
-
2206
- /**
2207
- Package description, listed in `npm search`.
2208
- */
2209
- description?: string;
2210
-
2211
- /**
2212
- Keywords associated with package, listed in `npm search`.
2213
- */
2214
- keywords?: string[];
2215
-
2216
- /**
2217
- The URL to the package's homepage.
2218
- */
2219
- homepage?: LiteralUnion<'.', string>;
2220
-
2221
- /**
2222
- The URL to the package's issue tracker and/or the email address to which issues should be reported.
2223
- */
2224
- bugs?: BugsLocation;
2225
-
2226
- /**
2227
- The license for the package.
2228
- */
2229
- license?: string;
2230
-
2231
- /**
2232
- The licenses for the package.
2233
- */
2234
- licenses?: Array<{
2235
- type?: string;
2236
- url?: string;
2237
- }>;
2238
-
2239
- author?: Person;
2240
-
2241
- /**
2242
- A list of people who contributed to the package.
2243
- */
2244
- contributors?: Person[];
2245
-
2246
- /**
2247
- A list of people who maintain the package.
2248
- */
2249
- maintainers?: Person[];
2250
-
2251
- /**
2252
- The files included in the package.
2253
- */
2254
- files?: string[];
2255
-
2256
- /**
2257
- Resolution algorithm for importing ".js" files from the package's scope.
2258
-
2259
- [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field)
2260
- */
2261
- type?: 'module' | 'commonjs';
2262
-
2263
- /**
2264
- The module ID that is the primary entry point to the program.
2265
- */
2266
- main?: string;
2267
-
2268
- /**
2269
- Subpath exports to define entry points of the package.
2270
-
2271
- [Read more.](https://nodejs.org/api/packages.html#subpath-exports)
2272
- */
2273
- exports?: Exports;
2274
-
2275
- /**
2276
- Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself.
2277
-
2278
- [Read more.](https://nodejs.org/api/packages.html#subpath-imports)
2279
- */
2280
- imports?: Imports;
2281
-
2282
- /**
2283
- The executable files that should be installed into the `PATH`.
2284
- */
2285
- bin?:
2286
- | string
2287
- | Partial<Record<string, string>>;
2288
-
2289
- /**
2290
- Filenames to put in place for the `man` program to find.
2291
- */
2292
- man?: string | string[];
2293
-
2294
- /**
2295
- Indicates the structure of the package.
2296
- */
2297
- directories?: DirectoryLocations;
2298
-
2299
- /**
2300
- Location for the code repository.
2301
- */
2302
- repository?:
2303
- | string
2304
- | {
2305
- type: string;
2306
- url: string;
2307
-
2308
- /**
2309
- Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo).
2310
-
2311
- [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md)
2312
- */
2313
- directory?: string;
2314
- };
2315
-
2316
- /**
2317
- Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point.
2318
- */
2319
- scripts?: Scripts;
2320
-
2321
- /**
2322
- Is used to set configuration parameters used in package scripts that persist across upgrades.
2323
- */
2324
- config?: JsonObject;
2325
-
2326
- /**
2327
- The dependencies of the package.
2328
- */
2329
- dependencies?: Dependency;
2330
-
2331
- /**
2332
- Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling.
2333
- */
2334
- devDependencies?: Dependency;
2335
-
2336
- /**
2337
- Dependencies that are skipped if they fail to install.
2338
- */
2339
- optionalDependencies?: Dependency;
2340
-
2341
- /**
2342
- Dependencies that will usually be required by the package user directly or via another dependency.
2343
- */
2344
- peerDependencies?: Dependency;
2345
-
2346
- /**
2347
- Indicate peer dependencies that are optional.
2348
- */
2349
- peerDependenciesMeta?: Partial<Record<string, {optional: true}>>;
2350
-
2351
- /**
2352
- Package names that are bundled when the package is published.
2353
- */
2354
- bundledDependencies?: string[];
2355
-
2356
- /**
2357
- Alias of `bundledDependencies`.
2358
- */
2359
- bundleDependencies?: string[];
2360
-
2361
- /**
2362
- Engines that this package runs on.
2363
- */
2364
- engines?: {
2365
- [EngineName in 'npm' | 'node' | string]?: string;
2366
- };
2367
-
2368
- /**
2369
- @deprecated
2370
- */
2371
- engineStrict?: boolean;
2372
-
2373
- /**
2374
- Operating systems the module runs on.
2375
- */
2376
- os?: Array<LiteralUnion<
2377
- | 'aix'
2378
- | 'darwin'
2379
- | 'freebsd'
2380
- | 'linux'
2381
- | 'openbsd'
2382
- | 'sunos'
2383
- | 'win32'
2384
- | '!aix'
2385
- | '!darwin'
2386
- | '!freebsd'
2387
- | '!linux'
2388
- | '!openbsd'
2389
- | '!sunos'
2390
- | '!win32',
2391
- string
2392
- >>;
2393
-
2394
- /**
2395
- CPU architectures the module runs on.
2396
- */
2397
- cpu?: Array<LiteralUnion<
2398
- | 'arm'
2399
- | 'arm64'
2400
- | 'ia32'
2401
- | 'mips'
2402
- | 'mipsel'
2403
- | 'ppc'
2404
- | 'ppc64'
2405
- | 's390'
2406
- | 's390x'
2407
- | 'x32'
2408
- | 'x64'
2409
- | '!arm'
2410
- | '!arm64'
2411
- | '!ia32'
2412
- | '!mips'
2413
- | '!mipsel'
2414
- | '!ppc'
2415
- | '!ppc64'
2416
- | '!s390'
2417
- | '!s390x'
2418
- | '!x32'
2419
- | '!x64',
2420
- string
2421
- >>;
2422
-
2423
- /**
2424
- If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally.
2425
-
2426
- @deprecated
2427
- */
2428
- preferGlobal?: boolean;
2429
-
2430
- /**
2431
- If set to `true`, then npm will refuse to publish it.
2432
- */
2433
- private?: boolean;
2434
-
2435
- /**
2436
- A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default.
2437
- */
2438
- publishConfig?: PublishConfig;
2439
-
2440
- /**
2441
- Describes and notifies consumers of a package's monetary support information.
2442
-
2443
- [Read more.](https://github.com/npm/rfcs/blob/main/implemented/0017-add-funding-support.md)
2444
- */
2445
- funding?: string | {
2446
- /**
2447
- The type of funding.
2448
- */
2449
- type?: LiteralUnion<
2450
- | 'github'
2451
- | 'opencollective'
2452
- | 'patreon'
2453
- | 'individual'
2454
- | 'foundation'
2455
- | 'corporation',
2456
- string
2457
- >;
2458
-
2459
- /**
2460
- The URL to the funding page.
2461
- */
2462
- url: string;
2463
- };
2464
-
2465
- /**
2466
- Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/).
2467
-
2468
- Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run your install command once in order to install all of them in a single pass.
2469
-
2470
- Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces.
2471
- */
2472
- workspaces?: WorkspacePattern[] | WorkspaceConfig;
2473
- }
2474
-
2475
- /**
2476
- Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions).
2477
- */
2478
- export type NodeJsStandard = {
2479
- /**
2480
- Defines which package manager is expected to be used when working on the current project. It can set to any of the [supported package managers](https://nodejs.org/api/corepack.html#supported-package-managers), and will ensure that your teams use the exact same package manager versions without having to install anything else than Node.js.
2481
-
2482
- __This field is currently experimental and needs to be opted-in; check the [Corepack](https://nodejs.org/api/corepack.html) page for details about the procedure.__
2483
-
2484
- @example
2485
- ```json
2486
- {
2487
- "packageManager": "<package manager name>@<version>"
2488
- }
2489
- ```
2490
- */
2491
- packageManager?: string;
2492
- };
2493
-
2494
- export type PublishConfig = {
2495
- /**
2496
- Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig).
2497
- */
2498
- [additionalProperties: string]: JsonValue | undefined;
2499
-
2500
- /**
2501
- When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public.
2502
- */
2503
- access?: 'public' | 'restricted';
2504
-
2505
- /**
2506
- The base URL of the npm registry.
2507
-
2508
- Default: `'https://registry.npmjs.org/'`
2509
- */
2510
- registry?: string;
2511
-
2512
- /**
2513
- The tag to publish the package under.
2514
-
2515
- Default: `'latest'`
2516
- */
2517
- tag?: string;
2518
- };
2519
- }
2520
-
2521
- /**
2522
- Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn.
2523
-
2524
- @category File
2525
- */
2526
- type PackageJson$1 =
2527
- JsonObject &
2528
- PackageJson$1.NodeJsStandard &
2529
- PackageJson$1.PackageJsonStandard &
2530
- PackageJson$1.NonStandardEntryPoints &
2531
- PackageJson$1.TypeScriptConfiguration &
2532
- PackageJson$1.YarnConfiguration &
2533
- PackageJson$1.JSPMConfiguration;
2534
-
2535
- type Prettify<T> = {
2536
- [K in keyof T]: T[K];
2537
- } & {};
2538
- type PartialDeep<T> = T extends object ? {
2539
- [P in keyof T]?: PartialDeep<T[P]>;
2540
- } : T;
2541
-
2542
- /**
2543
- * Union type representing the possible statuses of a prompt.
2544
- *
2545
- * - `'loading'`: The prompt is currently loading.
2546
- * - `'idle'`: The prompt is loaded and currently waiting for the user to
2547
- * submit an answer.
2548
- * - `'done'`: The user has submitted an answer and the prompt is finished.
2549
- * - `string`: Any other string: The prompt is in a custom state.
2550
- */
2551
- type Status = 'loading' | 'idle' | 'done' | (string & {});
2552
- type DefaultTheme = {
2553
- /**
2554
- * Prefix to prepend to the message. If a function is provided, it will be
2555
- * called with the current status of the prompt, and the return value will be
2556
- * used as the prefix.
2557
- *
2558
- * @remarks
2559
- * If `status === 'loading'`, this property is ignored and the spinner (styled
2560
- * by the `spinner` property) will be displayed instead.
2561
- *
2562
- * @defaultValue
2563
- * ```ts
2564
- * // import colors from 'yoctocolors-cjs';
2565
- * (status) => status === 'done' ? colors.green('✔') : colors.blue('?')
2566
- * ```
2567
- */
2568
- prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
2569
- /**
2570
- * Configuration for the spinner that is displayed when the prompt is in the
2571
- * `'loading'` state.
2572
- *
2573
- * We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
2574
- */
2575
- spinner: {
2576
- /**
2577
- * The time interval between frames, in milliseconds.
2578
- *
2579
- * @defaultValue
2580
- * ```ts
2581
- * 80
2582
- * ```
2583
- */
2584
- interval: number;
2585
- /**
2586
- * A list of frames to show for the spinner.
2587
- *
2588
- * @defaultValue
2589
- * ```ts
2590
- * ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
2591
- * ```
2592
- */
2593
- frames: string[];
2594
- };
2595
- /**
2596
- * Object containing functions to style different parts of the prompt.
2597
- */
2598
- style: {
2599
- /**
2600
- * Style to apply to the user's answer once it has been submitted.
2601
- *
2602
- * @param text - The user's answer.
2603
- * @returns The styled answer.
2604
- *
2605
- * @defaultValue
2606
- * ```ts
2607
- * // import colors from 'yoctocolors-cjs';
2608
- * (text) => colors.cyan(text)
2609
- * ```
2610
- */
2611
- answer: (text: string) => string;
2612
- /**
2613
- * Style to apply to the message displayed to the user.
2614
- *
2615
- * @param text - The message to style.
2616
- * @param status - The current status of the prompt.
2617
- * @returns The styled message.
2618
- *
2619
- * @defaultValue
2620
- * ```ts
2621
- * // import colors from 'yoctocolors-cjs';
2622
- * (text, status) => colors.bold(text)
2623
- * ```
2624
- */
2625
- message: (text: string, status: Status) => string;
2626
- /**
2627
- * Style to apply to error messages.
2628
- *
2629
- * @param text - The error message.
2630
- * @returns The styled error message.
2631
- *
2632
- * @defaultValue
2633
- * ```ts
2634
- * // import colors from 'yoctocolors-cjs';
2635
- * (text) => colors.red(`> ${text}`)
2636
- * ```
2637
- */
2638
- error: (text: string) => string;
2639
- /**
2640
- * Style to apply to the default answer when one is provided.
2641
- *
2642
- * @param text - The default answer.
2643
- * @returns The styled default answer.
2644
- *
2645
- * @defaultValue
2646
- * ```ts
2647
- * // import colors from 'yoctocolors-cjs';
2648
- * (text) => colors.dim(`(${text})`)
2649
- * ```
2650
- */
2651
- defaultAnswer: (text: string) => string;
2652
- /**
2653
- * Style to apply to help text.
2654
- *
2655
- * @param text - The help text.
2656
- * @returns The styled help text.
2657
- *
2658
- * @defaultValue
2659
- * ```ts
2660
- * // import colors from 'yoctocolors-cjs';
2661
- * (text) => colors.dim(text)
2662
- * ```
2663
- */
2664
- help: (text: string) => string;
2665
- /**
2666
- * Style to apply to highlighted text.
2667
- *
2668
- * @param text - The text to highlight.
2669
- * @returns The highlighted text.
2670
- *
2671
- * @defaultValue
2672
- * ```ts
2673
- * // import colors from 'yoctocolors-cjs';
2674
- * (text) => colors.cyan(text)
2675
- * ```
2676
- */
2677
- highlight: (text: string) => string;
2678
- /**
2679
- * Style to apply to keyboard keys referred to in help texts.
2680
- *
2681
- * @param text - The key to style.
2682
- * @returns The styled key.
2683
- *
2684
- * @defaultValue
2685
- * ```ts
2686
- * // import colors from 'yoctocolors-cjs';
2687
- * (text) => colors.cyan(colors.bold(`<${text}>`))
2688
- * ```
2689
- */
2690
- key: (text: string) => string;
2691
- };
2692
- };
2693
- type Theme<Extension extends object = object> = Prettify<Extension & DefaultTheme>;
2694
-
2695
- type NormalizedPackageJson = Package & PackageJson;
2696
- type PackageJson = PackageJson$1;
2697
- type Cache<T = any> = Map<string, T>;
2698
- type EnsurePackagesOptions = {
2699
- confirm?: {
2700
- default?: boolean;
2701
- message: string | ((packages: string[]) => string);
2702
- theme?: PartialDeep<Theme>;
2703
- transformer?: (value: boolean) => string;
2704
- };
2705
- cwd?: URL | string;
2706
- deps?: boolean;
2707
- devDeps?: boolean;
2708
- installPackage?: Omit<InstallPackageOptions, "cwd" | "dev">;
2709
- logger?: {
2710
- warn: (message: string) => void;
2711
- };
2712
- peerDeps?: boolean;
2713
- throwOnWarn?: boolean;
2714
- };
2715
-
2716
- type ReadOptions = {
2717
- cache?: FindPackageJsonCache | boolean;
2718
- ignoreWarnings?: (RegExp | string)[];
2719
- strict?: boolean;
2720
- };
2721
- type FindPackageJsonCache = Cache<NormalizedReadResult>;
2722
- type NormalizedReadResult = {
2723
- packageJson: NormalizedPackageJson;
2724
- path: string;
2725
- };
2726
- declare const findPackageJson: (cwd?: URL | string, options?: ReadOptions) => Promise<NormalizedReadResult>;
2727
- declare const findPackageJsonSync: (cwd?: URL | string, options?: ReadOptions) => NormalizedReadResult;
2728
- declare const writePackageJson: <T = PackageJson>(data: T, options?: WriteJsonOptions & {
2729
- cwd?: URL | string;
2730
- }) => Promise<void>;
2731
- declare const writePackageJsonSync: <T = PackageJson>(data: T, options?: WriteJsonOptions & {
2732
- cwd?: URL | string;
2733
- }) => void;
2734
- declare const parsePackageJsonSync: (packageFile: JsonObject | string, options?: {
2735
- ignoreWarnings?: (RegExp | string)[];
2736
- resolveCatalogs?: boolean;
2737
- strict?: boolean;
2738
- }) => NormalizedPackageJson;
2739
- declare const parsePackageJson: (packageFile: JsonObject | string, options?: {
2740
- ignoreWarnings?: (RegExp | string)[];
2741
- resolveCatalogs?: boolean;
2742
- strict?: boolean;
2743
- }) => Promise<NormalizedPackageJson>;
2744
- declare const getPackageJsonProperty: <T = unknown>(packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>, defaultValue?: T) => T;
2745
- declare const hasPackageJsonProperty: (packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>) => boolean;
2746
- declare const hasPackageJsonAnyDependency: (packageJson: NormalizedPackageJson, arguments_: string[], options?: {
2747
- peerDeps?: boolean;
2748
- }) => boolean;
2749
- declare const ensurePackages: (packageJson: NormalizedPackageJson, packages: string[], installKey?: "dependencies" | "devDependencies", options?: EnsurePackagesOptions) => Promise<void>;
2750
-
2751
- export { type EnsurePackagesOptions as E, type FindPackageJsonCache as F, type NormalizedReadResult as N, type PackageJson as P, findPackageJsonSync as a, hasPackageJsonProperty as b, writePackageJsonSync as c, type NormalizedPackageJson as d, ensurePackages as e, findPackageJson as f, getPackageJsonProperty as g, hasPackageJsonAnyDependency as h, parsePackageJsonSync as i, parsePackageJson as p, writePackageJson as w };