@visulima/package 5.0.12 → 5.0.14
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.
- package/CHANGELOG.md +9 -0
- package/LICENSE.md +126 -61
- package/dist/error.js +1 -1
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/lockfile.js +1 -1
- package/dist/monorepo.js +1 -1
- package/dist/package-json.d.ts +3 -4
- package/dist/package-json.js +3 -3
- package/dist/package-manager.js +3 -3
- package/dist/package.js +1 -1
- package/dist/packem_shared/PackageNotFoundError-PwPSQ1F3.js +1 -0
- package/dist/packem_shared/json-value.d-AIF0oxA6.d.ts +29 -0
- package/dist/packem_shared/package-json.d-XOvCk6yp.d.ts +3167 -0
- package/dist/pnpm.d.ts +1 -1
- package/dist/pnpm.js +1 -1
- package/package.json +25 -25
- package/dist/packem_shared/PackageNotFoundError-Bi41exhP.js +0 -1
- package/dist/packem_shared/package-json.d-62php2nC.d.ts +0 -186
|
@@ -0,0 +1,3167 @@
|
|
|
1
|
+
import { WriteJsonOptions } from '@visulima/fs';
|
|
2
|
+
import { InstallPackageOptions } from '@antfu/install-pkg';
|
|
3
|
+
import { Package } from 'normalize-package-data';
|
|
4
|
+
import { a as JsonValue, J as JsonObject } from "./json-value.d-AIF0oxA6.js";
|
|
5
|
+
import tag from 'tagged-tag';
|
|
6
|
+
/**
|
|
7
|
+
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
|
|
8
|
+
|
|
9
|
+
@category Type
|
|
10
|
+
*/
|
|
11
|
+
type Primitive = null | undefined | string | number | boolean | symbol | bigint;
|
|
12
|
+
/**
|
|
13
|
+
Matches any digit as a string ('0'-'9').
|
|
14
|
+
|
|
15
|
+
@example
|
|
16
|
+
```
|
|
17
|
+
import type {DigitCharacter} from 'type-fest';
|
|
18
|
+
|
|
19
|
+
const a: DigitCharacter = '0'; // Valid
|
|
20
|
+
// @ts-expect-error
|
|
21
|
+
const b: DigitCharacter = 0; // Invalid
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
@category Type
|
|
25
|
+
*/
|
|
26
|
+
type DigitCharacter = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
|
27
|
+
/**
|
|
28
|
+
Returns a boolean for whether the given type is `any`.
|
|
29
|
+
|
|
30
|
+
@link https://stackoverflow.com/a/49928360/1490091
|
|
31
|
+
|
|
32
|
+
Useful in type utilities, such as disallowing `any`s to be passed to a function.
|
|
33
|
+
|
|
34
|
+
@example
|
|
35
|
+
```
|
|
36
|
+
import type {IsAny} from 'type-fest';
|
|
37
|
+
|
|
38
|
+
const typedObject = {a: 1, b: 2} as const;
|
|
39
|
+
const anyObject: any = {a: 1, b: 2};
|
|
40
|
+
|
|
41
|
+
function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(object: O, key: K) {
|
|
42
|
+
return object[key];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const typedA = get(typedObject, 'a');
|
|
46
|
+
//=> 1
|
|
47
|
+
|
|
48
|
+
const anyA = get(anyObject, 'a');
|
|
49
|
+
//=> any
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
@category Type Guard
|
|
53
|
+
@category Utilities
|
|
54
|
+
*/
|
|
55
|
+
type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
|
|
56
|
+
/**
|
|
57
|
+
Returns a boolean for whether the given key is an optional key of type.
|
|
58
|
+
|
|
59
|
+
This is useful when writing utility types or schema validators that need to differentiate `optional` keys.
|
|
60
|
+
|
|
61
|
+
@example
|
|
62
|
+
```
|
|
63
|
+
import type {IsOptionalKeyOf} from 'type-fest';
|
|
64
|
+
|
|
65
|
+
type User = {
|
|
66
|
+
name: string;
|
|
67
|
+
surname: string;
|
|
68
|
+
|
|
69
|
+
luckyNumber?: number;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type Admin = {
|
|
73
|
+
name: string;
|
|
74
|
+
surname?: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
type T1 = IsOptionalKeyOf<User, 'luckyNumber'>;
|
|
78
|
+
//=> true
|
|
79
|
+
|
|
80
|
+
type T2 = IsOptionalKeyOf<User, 'name'>;
|
|
81
|
+
//=> false
|
|
82
|
+
|
|
83
|
+
type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>;
|
|
84
|
+
//=> boolean
|
|
85
|
+
|
|
86
|
+
type T4 = IsOptionalKeyOf<User | Admin, 'name'>;
|
|
87
|
+
//=> false
|
|
88
|
+
|
|
89
|
+
type T5 = IsOptionalKeyOf<User | Admin, 'surname'>;
|
|
90
|
+
//=> boolean
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
@category Type Guard
|
|
94
|
+
@category Utilities
|
|
95
|
+
*/
|
|
96
|
+
type IsOptionalKeyOf<Type extends object, Key extends keyof Type> = IsAny<Type | Key> extends true ? never : Key extends keyof Type ? Type extends Record<Key, Type[Key]> ? false : true : false;
|
|
97
|
+
/**
|
|
98
|
+
Extract all optional keys from the given type.
|
|
99
|
+
|
|
100
|
+
This is useful when you want to create a new type that contains different type values for the optional keys only.
|
|
101
|
+
|
|
102
|
+
@example
|
|
103
|
+
```
|
|
104
|
+
import type {OptionalKeysOf, Except} from 'type-fest';
|
|
105
|
+
|
|
106
|
+
type User = {
|
|
107
|
+
name: string;
|
|
108
|
+
surname: string;
|
|
109
|
+
|
|
110
|
+
luckyNumber?: number;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const REMOVE_FIELD = Symbol('remove field symbol');
|
|
114
|
+
type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
|
|
115
|
+
[Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const update1: UpdateOperation<User> = {
|
|
119
|
+
name: 'Alice',
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const update2: UpdateOperation<User> = {
|
|
123
|
+
name: 'Bob',
|
|
124
|
+
luckyNumber: REMOVE_FIELD,
|
|
125
|
+
};
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
@category Utilities
|
|
129
|
+
*/
|
|
130
|
+
type OptionalKeysOf<Type extends object> = Type extends unknown // For distributing `Type`
|
|
131
|
+
? (keyof { [Key in keyof Type as IsOptionalKeyOf<Type, Key> extends false ? never : Key]: never; }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf<Type>` is always assignable to `keyof Type`
|
|
132
|
+
: never; // Should never happen
|
|
133
|
+
/**
|
|
134
|
+
Extract all required keys from the given type.
|
|
135
|
+
|
|
136
|
+
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...
|
|
137
|
+
|
|
138
|
+
@example
|
|
139
|
+
```
|
|
140
|
+
import type {RequiredKeysOf} from 'type-fest';
|
|
141
|
+
|
|
142
|
+
declare function createValidation<
|
|
143
|
+
Entity extends object,
|
|
144
|
+
Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>,
|
|
145
|
+
>(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean;
|
|
146
|
+
|
|
147
|
+
type User = {
|
|
148
|
+
name: string;
|
|
149
|
+
surname: string;
|
|
150
|
+
luckyNumber?: number;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const validator1 = createValidation<User>('name', value => value.length < 25);
|
|
154
|
+
const validator2 = createValidation<User>('surname', value => value.length < 25);
|
|
155
|
+
|
|
156
|
+
// @ts-expect-error
|
|
157
|
+
const validator3 = createValidation<User>('luckyNumber', value => value > 0);
|
|
158
|
+
// Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'.
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
@category Utilities
|
|
162
|
+
*/
|
|
163
|
+
type RequiredKeysOf<Type extends object> = Type extends unknown // For distributing `Type`
|
|
164
|
+
? Exclude<keyof Type, OptionalKeysOf<Type>> : never; // Should never happen
|
|
165
|
+
/**
|
|
166
|
+
Returns a boolean for whether the given type is `never`.
|
|
167
|
+
|
|
168
|
+
@link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
|
|
169
|
+
@link https://stackoverflow.com/a/53984913/10292952
|
|
170
|
+
@link https://www.zhenghao.io/posts/ts-never
|
|
171
|
+
|
|
172
|
+
Useful in type utilities, such as checking if something does not occur.
|
|
173
|
+
|
|
174
|
+
@example
|
|
175
|
+
```
|
|
176
|
+
import type {IsNever, And} from 'type-fest';
|
|
177
|
+
|
|
178
|
+
type A = IsNever<never>;
|
|
179
|
+
//=> true
|
|
180
|
+
|
|
181
|
+
type B = IsNever<any>;
|
|
182
|
+
//=> false
|
|
183
|
+
|
|
184
|
+
type C = IsNever<unknown>;
|
|
185
|
+
//=> false
|
|
186
|
+
|
|
187
|
+
type D = IsNever<never[]>;
|
|
188
|
+
//=> false
|
|
189
|
+
|
|
190
|
+
type E = IsNever<object>;
|
|
191
|
+
//=> false
|
|
192
|
+
|
|
193
|
+
type F = IsNever<string>;
|
|
194
|
+
//=> false
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
@example
|
|
198
|
+
```
|
|
199
|
+
import type {IsNever} from 'type-fest';
|
|
200
|
+
|
|
201
|
+
type IsTrue<T> = T extends true ? true : false;
|
|
202
|
+
|
|
203
|
+
// When a distributive conditional is instantiated with `never`, the entire conditional results in `never`.
|
|
204
|
+
type A = IsTrue<never>;
|
|
205
|
+
//=> never
|
|
206
|
+
|
|
207
|
+
// If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional.
|
|
208
|
+
type IsTrueFixed<T> =
|
|
209
|
+
IsNever<T> extends true ? false : T extends true ? true : false;
|
|
210
|
+
|
|
211
|
+
type B = IsTrueFixed<never>;
|
|
212
|
+
//=> false
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
@category Type Guard
|
|
216
|
+
@category Utilities
|
|
217
|
+
*/
|
|
218
|
+
type IsNever<T> = [T] extends [never] ? true : false;
|
|
219
|
+
/**
|
|
220
|
+
An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
|
|
221
|
+
|
|
222
|
+
Use-cases:
|
|
223
|
+
- 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'>`.
|
|
224
|
+
|
|
225
|
+
Note:
|
|
226
|
+
- 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'`.
|
|
227
|
+
- Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
|
|
228
|
+
|
|
229
|
+
@example
|
|
230
|
+
```
|
|
231
|
+
import type {If} from 'type-fest';
|
|
232
|
+
|
|
233
|
+
type A = If<true, 'yes', 'no'>;
|
|
234
|
+
//=> 'yes'
|
|
235
|
+
|
|
236
|
+
type B = If<false, 'yes', 'no'>;
|
|
237
|
+
//=> 'no'
|
|
238
|
+
|
|
239
|
+
type C = If<boolean, 'yes', 'no'>;
|
|
240
|
+
//=> 'yes' | 'no'
|
|
241
|
+
|
|
242
|
+
type D = If<any, 'yes', 'no'>;
|
|
243
|
+
//=> 'yes' | 'no'
|
|
244
|
+
|
|
245
|
+
type E = If<never, 'yes', 'no'>;
|
|
246
|
+
//=> 'no'
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
@example
|
|
250
|
+
```
|
|
251
|
+
import type {If, IsAny, IsNever} from 'type-fest';
|
|
252
|
+
|
|
253
|
+
type A = If<IsAny<unknown>, 'is any', 'not any'>;
|
|
254
|
+
//=> 'not any'
|
|
255
|
+
|
|
256
|
+
type B = If<IsNever<never>, 'is never', 'not never'>;
|
|
257
|
+
//=> 'is never'
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
@example
|
|
261
|
+
```
|
|
262
|
+
import type {If, IsEqual} from 'type-fest';
|
|
263
|
+
|
|
264
|
+
type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
|
|
265
|
+
|
|
266
|
+
type A = IfEqual<string, string, 'equal', 'not equal'>;
|
|
267
|
+
//=> 'equal'
|
|
268
|
+
|
|
269
|
+
type B = IfEqual<string, number, 'equal', 'not equal'>;
|
|
270
|
+
//=> 'not equal'
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Note: Sometimes using the `If` type can make an implementation non–tail-recursive, which can impact performance. In such cases, it’s better to use a conditional directly. Refer to the following example:
|
|
274
|
+
|
|
275
|
+
@example
|
|
276
|
+
```
|
|
277
|
+
import type {If, IsEqual, StringRepeat} from 'type-fest';
|
|
278
|
+
|
|
279
|
+
type HundredZeroes = StringRepeat<'0', 100>;
|
|
280
|
+
|
|
281
|
+
// The following implementation is not tail recursive
|
|
282
|
+
type Includes<S extends string, Char extends string> =
|
|
283
|
+
S extends `${infer First}${infer Rest}`
|
|
284
|
+
? If<IsEqual<First, Char>,
|
|
285
|
+
'found',
|
|
286
|
+
Includes<Rest, Char>>
|
|
287
|
+
: 'not found';
|
|
288
|
+
|
|
289
|
+
// Hence, instantiations with long strings will fail
|
|
290
|
+
// @ts-expect-error
|
|
291
|
+
type Fails = Includes<HundredZeroes, '1'>;
|
|
292
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
293
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
294
|
+
|
|
295
|
+
// However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
|
|
296
|
+
type IncludesWithoutIf<S extends string, Char extends string> =
|
|
297
|
+
S extends `${infer First}${infer Rest}`
|
|
298
|
+
? IsEqual<First, Char> extends true
|
|
299
|
+
? 'found'
|
|
300
|
+
: IncludesWithoutIf<Rest, Char>
|
|
301
|
+
: 'not found';
|
|
302
|
+
|
|
303
|
+
// Now, instantiations with long strings will work
|
|
304
|
+
type Works = IncludesWithoutIf<HundredZeroes, '1'>;
|
|
305
|
+
//=> 'not found'
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
@category Type Guard
|
|
309
|
+
@category Utilities
|
|
310
|
+
*/
|
|
311
|
+
type If<Type extends boolean, IfBranch, ElseBranch> = IsNever<Type> extends true ? ElseBranch : Type extends true ? IfBranch : ElseBranch;
|
|
312
|
+
/**
|
|
313
|
+
Represents an array with `unknown` value.
|
|
314
|
+
|
|
315
|
+
Use case: You want a type that all arrays can be assigned to, but you don't care about the value.
|
|
316
|
+
|
|
317
|
+
@example
|
|
318
|
+
```
|
|
319
|
+
import type {UnknownArray} from 'type-fest';
|
|
320
|
+
|
|
321
|
+
type IsArray<T> = T extends UnknownArray ? true : false;
|
|
322
|
+
|
|
323
|
+
type A = IsArray<['foo']>;
|
|
324
|
+
//=> true
|
|
325
|
+
|
|
326
|
+
type B = IsArray<readonly number[]>;
|
|
327
|
+
//=> true
|
|
328
|
+
|
|
329
|
+
type C = IsArray<string>;
|
|
330
|
+
//=> false
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
@category Type
|
|
334
|
+
@category Array
|
|
335
|
+
*/
|
|
336
|
+
type UnknownArray = readonly unknown[];
|
|
337
|
+
/**
|
|
338
|
+
Matches any primitive, `void`, `Date`, or `RegExp` value.
|
|
339
|
+
*/
|
|
340
|
+
type BuiltIns = Primitive | void | Date | RegExp;
|
|
341
|
+
/**
|
|
342
|
+
Matches non-recursive types.
|
|
343
|
+
*/
|
|
344
|
+
type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown) | Promise<unknown>;
|
|
345
|
+
/**
|
|
346
|
+
Matches maps, sets, or arrays.
|
|
347
|
+
*/
|
|
348
|
+
type MapsSetsOrArrays = ReadonlyMap<unknown, unknown> | WeakMap<WeakKey, unknown> | ReadonlySet<unknown> | WeakSet<WeakKey> | UnknownArray;
|
|
349
|
+
/**
|
|
350
|
+
Returns a boolean for whether A is false.
|
|
351
|
+
|
|
352
|
+
@example
|
|
353
|
+
```
|
|
354
|
+
type A = Not<true>;
|
|
355
|
+
//=> false
|
|
356
|
+
|
|
357
|
+
type B = Not<false>;
|
|
358
|
+
//=> true
|
|
359
|
+
```
|
|
360
|
+
*/
|
|
361
|
+
type Not<A extends boolean> = A extends true ? false : A extends false ? true : never;
|
|
362
|
+
/**
|
|
363
|
+
An if-else-like type that resolves depending on whether the given type is `any` or `never`.
|
|
364
|
+
|
|
365
|
+
@example
|
|
366
|
+
```
|
|
367
|
+
// When `T` is neither `any` nor `never` (like `string`) => Returns `IfNot` branch
|
|
368
|
+
type A = IfNotAnyOrNever<string, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
369
|
+
//=> 'VALID'
|
|
370
|
+
|
|
371
|
+
// When `T` is `any` => Returns `IfAny` branch
|
|
372
|
+
type B = IfNotAnyOrNever<any, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
373
|
+
//=> 'IS_ANY'
|
|
374
|
+
|
|
375
|
+
// When `T` is `never` => Returns `IfNever` branch
|
|
376
|
+
type C = IfNotAnyOrNever<never, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
377
|
+
//=> 'IS_NEVER'
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Note: Wrapping a tail-recursive type with `IfNotAnyOrNever` makes the implementation non-tail-recursive. To fix this, move the recursion into a helper type. Refer to the following example:
|
|
381
|
+
|
|
382
|
+
@example
|
|
383
|
+
```ts
|
|
384
|
+
import type {StringRepeat} from 'type-fest';
|
|
385
|
+
|
|
386
|
+
type NineHundredNinetyNineSpaces = StringRepeat<' ', 999>;
|
|
387
|
+
|
|
388
|
+
// The following implementation is not tail recursive
|
|
389
|
+
type TrimLeft<S extends string> = IfNotAnyOrNever<S, {ifNot: S extends ` ${infer R}` ? TrimLeft<R> : S}>;
|
|
390
|
+
|
|
391
|
+
// Hence, instantiations with long strings will fail
|
|
392
|
+
// @ts-expect-error
|
|
393
|
+
type T1 = TrimLeft<NineHundredNinetyNineSpaces>;
|
|
394
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
395
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
396
|
+
|
|
397
|
+
// To fix this, move the recursion into a helper type
|
|
398
|
+
type TrimLeftOptimised<S extends string> = IfNotAnyOrNever<S, {ifNot: _TrimLeftOptimised<S>}>;
|
|
399
|
+
|
|
400
|
+
type _TrimLeftOptimised<S extends string> = S extends ` ${infer R}` ? _TrimLeftOptimised<R> : S;
|
|
401
|
+
|
|
402
|
+
type T2 = TrimLeftOptimised<NineHundredNinetyNineSpaces>;
|
|
403
|
+
//=> ''
|
|
404
|
+
```
|
|
405
|
+
*/
|
|
406
|
+
type IfNotAnyOrNever<T, Cases extends {
|
|
407
|
+
ifNot: unknown;
|
|
408
|
+
ifAny?: unknown;
|
|
409
|
+
ifNever?: unknown;
|
|
410
|
+
}> = IsAny<T> extends true ? 'ifAny' extends keyof Cases ? Cases['ifAny'] : any : IsNever<T> extends true ? 'ifNever' extends keyof Cases ? Cases['ifNever'] : never : Cases['ifNot'];
|
|
411
|
+
/**
|
|
412
|
+
Indicates the value of `exactOptionalPropertyTypes` compiler option.
|
|
413
|
+
*/
|
|
414
|
+
type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extends [string?] ? false : true;
|
|
415
|
+
/**
|
|
416
|
+
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.
|
|
417
|
+
|
|
418
|
+
@example
|
|
419
|
+
```
|
|
420
|
+
type A = CollapseRestElement<[string, string, ...number[]]>;
|
|
421
|
+
//=> [string, string, number]
|
|
422
|
+
|
|
423
|
+
type B = CollapseRestElement<[...string[], number, number]>;
|
|
424
|
+
//=> [string, number, number]
|
|
425
|
+
|
|
426
|
+
type C = CollapseRestElement<[string, string, ...Array<number | bigint>]>;
|
|
427
|
+
//=> [string, string, number | bigint]
|
|
428
|
+
|
|
429
|
+
type D = CollapseRestElement<[string, number]>;
|
|
430
|
+
//=> [string, number]
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
Note: Optional modifiers (`?`) are removed from elements unless the `exactOptionalPropertyTypes` compiler option is disabled. When disabled, there's an additional `| undefined` for optional elements.
|
|
434
|
+
|
|
435
|
+
@example
|
|
436
|
+
```
|
|
437
|
+
// `exactOptionalPropertyTypes` enabled
|
|
438
|
+
type A = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
439
|
+
//=> [string, string, number]
|
|
440
|
+
|
|
441
|
+
// `exactOptionalPropertyTypes` disabled
|
|
442
|
+
type B = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
443
|
+
//=> [string | undefined, string | undefined, number]
|
|
444
|
+
```
|
|
445
|
+
*/
|
|
446
|
+
type CollapseRestElement<TArray extends UnknownArray> = IfNotAnyOrNever<TArray, {
|
|
447
|
+
ifNot: _CollapseRestElement<TArray>;
|
|
448
|
+
}>;
|
|
449
|
+
type _CollapseRestElement<TArray extends UnknownArray, ForwardAccumulator extends UnknownArray = [], BackwardAccumulator extends UnknownArray = []> = TArray extends UnknownArray // For distributing `TArray`
|
|
450
|
+
? keyof TArray & `${number}` extends never ?
|
|
451
|
+
// Enters this branch, if `TArray` is empty (e.g., []),
|
|
452
|
+
// or `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
|
|
453
|
+
TArray extends readonly [...infer Rest, infer Last] ? _CollapseRestElement<Rest, ForwardAccumulator, [Last, ...BackwardAccumulator]> // Accumulate elements that are present after the rest element.
|
|
454
|
+
: TArray extends readonly [] ? [...ForwardAccumulator, ...BackwardAccumulator] : [...ForwardAccumulator, TArray[number], ...BackwardAccumulator] // Add the rest element between the accumulated elements.
|
|
455
|
+
: TArray extends readonly [(infer First)?, ...infer Rest] ? _CollapseRestElement<Rest, [...ForwardAccumulator, '0' extends OptionalKeysOf<TArray> ? If<IsExactOptionalPropertyTypesEnabled, First, First | undefined> // Add `| undefined` for optional elements, if `exactOptionalPropertyTypes` is disabled.
|
|
456
|
+
: First], BackwardAccumulator> : never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays.
|
|
457
|
+
: never; // Should never happen
|
|
458
|
+
type _Numeric = number | bigint;
|
|
459
|
+
type Zero = 0 | 0n;
|
|
460
|
+
/**
|
|
461
|
+
Matches the hidden `Infinity` type.
|
|
462
|
+
|
|
463
|
+
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
|
|
464
|
+
|
|
465
|
+
@see {@link NegativeInfinity}
|
|
466
|
+
|
|
467
|
+
@category Numeric
|
|
468
|
+
*/
|
|
469
|
+
// See https://github.com/microsoft/TypeScript/issues/31752
|
|
470
|
+
// eslint-disable-next-line no-loss-of-precision
|
|
471
|
+
type PositiveInfinity = 1e999;
|
|
472
|
+
/**
|
|
473
|
+
Matches the hidden `-Infinity` type.
|
|
474
|
+
|
|
475
|
+
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
|
|
476
|
+
|
|
477
|
+
@see {@link PositiveInfinity}
|
|
478
|
+
|
|
479
|
+
@category Numeric
|
|
480
|
+
*/
|
|
481
|
+
// See https://github.com/microsoft/TypeScript/issues/31752
|
|
482
|
+
// eslint-disable-next-line no-loss-of-precision
|
|
483
|
+
type NegativeInfinity = -1e999;
|
|
484
|
+
/**
|
|
485
|
+
A negative `number`/`bigint` (`-∞ < x < 0`)
|
|
486
|
+
|
|
487
|
+
Use-case: Validating and documenting parameters.
|
|
488
|
+
|
|
489
|
+
@see {@link NegativeInteger}
|
|
490
|
+
@see {@link NonNegative}
|
|
491
|
+
|
|
492
|
+
@category Numeric
|
|
493
|
+
*/
|
|
494
|
+
type Negative<T extends _Numeric> = T extends Zero ? never : `${T}` extends `-${string}` ? T : never;
|
|
495
|
+
/**
|
|
496
|
+
Returns a boolean for whether the given number is a negative number.
|
|
497
|
+
|
|
498
|
+
@see {@link Negative}
|
|
499
|
+
|
|
500
|
+
@example
|
|
501
|
+
```
|
|
502
|
+
import type {IsNegative} from 'type-fest';
|
|
503
|
+
|
|
504
|
+
type ShouldBeFalse = IsNegative<1>;
|
|
505
|
+
type ShouldBeTrue = IsNegative<-1>;
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
@category Numeric
|
|
509
|
+
*/
|
|
510
|
+
type IsNegative<T extends _Numeric> = T extends Negative<T> ? true : false;
|
|
511
|
+
// eslint-disable-next-line type-fest/require-exported-types
|
|
512
|
+
type TagContainer<Token> = {
|
|
513
|
+
readonly [tag]: Token;
|
|
514
|
+
};
|
|
515
|
+
type Tag<Token extends PropertyKey, TagMetadata> = TagContainer<{ [K in Token]: TagMetadata; }>;
|
|
516
|
+
/**
|
|
517
|
+
Create a [tagged type](https://medium.com/@KevinBGreene/surviving-the-typescript-ecosystem-branding-and-type-tagging-6cf6e516523d) that can support [multiple tags](https://github.com/sindresorhus/type-fest/issues/665) and [per-tag metadata](https://medium.com/@ethanresnick/advanced-typescript-tagged-types-improved-with-type-level-metadata-5072fc125fcf).
|
|
518
|
+
|
|
519
|
+
A type returned by `Tagged` can be passed to `Tagged` again, to create a type with multiple tags.
|
|
520
|
+
|
|
521
|
+
A tag's name is usually a string (and must be a string, number, or symbol), but each application of a tag can also contain an arbitrary type as its "metadata". See {@link GetTagMetadata} for examples and explanation.
|
|
522
|
+
|
|
523
|
+
A type `A` returned by `Tagged` is assignable to another type `B` returned by `Tagged` if and only if:
|
|
524
|
+
- the underlying (untagged) type of `A` is assignable to the underlying type of `B`;
|
|
525
|
+
- `A` contains at least all the tags `B` has;
|
|
526
|
+
- and the metadata type for each of `A`'s tags is assignable to the metadata type of `B`'s corresponding tag.
|
|
527
|
+
|
|
528
|
+
There have been several discussions about adding similar features to TypeScript. Unfortunately, nothing has (yet) moved forward:
|
|
529
|
+
- [Microsoft/TypeScript#202](https://github.com/microsoft/TypeScript/issues/202)
|
|
530
|
+
- [Microsoft/TypeScript#4895](https://github.com/microsoft/TypeScript/issues/4895)
|
|
531
|
+
- [Microsoft/TypeScript#33290](https://github.com/microsoft/TypeScript/pull/33290)
|
|
532
|
+
|
|
533
|
+
@example
|
|
534
|
+
```
|
|
535
|
+
import type {Tagged} from 'type-fest';
|
|
536
|
+
|
|
537
|
+
type AccountNumber = Tagged<number, 'AccountNumber'>;
|
|
538
|
+
type AccountBalance = Tagged<number, 'AccountBalance'>;
|
|
539
|
+
|
|
540
|
+
function createAccountNumber(): AccountNumber {
|
|
541
|
+
// As you can see, casting from a `number` (the underlying type being tagged) is allowed.
|
|
542
|
+
return 2 as AccountNumber;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
declare function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance;
|
|
546
|
+
|
|
547
|
+
// This will compile successfully.
|
|
548
|
+
getMoneyForAccount(createAccountNumber());
|
|
549
|
+
|
|
550
|
+
// But this won't, because it has to be explicitly passed as an `AccountNumber` type!
|
|
551
|
+
// Critically, you could not accidentally use an `AccountBalance` as an `AccountNumber`.
|
|
552
|
+
// @ts-expect-error
|
|
553
|
+
getMoneyForAccount(2);
|
|
554
|
+
|
|
555
|
+
// You can also use tagged values like their underlying, untagged type.
|
|
556
|
+
// I.e., this will compile successfully because an `AccountNumber` can be used as a regular `number`.
|
|
557
|
+
// In this sense, the underlying base type is not hidden, which differentiates tagged types from opaque types in other languages.
|
|
558
|
+
const accountNumber = createAccountNumber() + 2;
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
@example
|
|
562
|
+
```
|
|
563
|
+
import type {Tagged} from 'type-fest';
|
|
564
|
+
|
|
565
|
+
// You can apply multiple tags to a type by using `Tagged` repeatedly.
|
|
566
|
+
type Url = Tagged<string, 'URL'>;
|
|
567
|
+
type SpecialCacheKey = Tagged<Url, 'SpecialCacheKey'>;
|
|
568
|
+
|
|
569
|
+
// You can also pass a union of tag names, so this is equivalent to the above, although it doesn't give you the ability to assign distinct metadata to each tag.
|
|
570
|
+
type SpecialCacheKey2 = Tagged<string, 'URL' | 'SpecialCacheKey'>;
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
@category Type
|
|
574
|
+
*/
|
|
575
|
+
type Tagged<Type, TagName extends PropertyKey, TagMetadata = never> = Type & Tag<TagName, TagMetadata>;
|
|
576
|
+
/**
|
|
577
|
+
Get the untagged portion of a tagged type created with `Tagged`.
|
|
578
|
+
|
|
579
|
+
Why is this necessary?
|
|
580
|
+
|
|
581
|
+
1. Use a `Tagged` type as object keys
|
|
582
|
+
2. Prevent TS4058 error: "Return type of exported function has or is using name X from external module Y but cannot be named"
|
|
583
|
+
|
|
584
|
+
@example
|
|
585
|
+
```
|
|
586
|
+
import type {Tagged, UnwrapTagged} from 'type-fest';
|
|
587
|
+
|
|
588
|
+
type AccountType = Tagged<'SAVINGS' | 'CHECKING', 'AccountType'>;
|
|
589
|
+
|
|
590
|
+
const moneyByAccountType: Record<UnwrapTagged<AccountType>, number> = {
|
|
591
|
+
SAVINGS: 99,
|
|
592
|
+
CHECKING: 0.1,
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
// Without UnwrapTagged, the following expression would throw a type error.
|
|
596
|
+
const money = moneyByAccountType.SAVINGS; // TS error: Property 'SAVINGS' does not exist
|
|
597
|
+
|
|
598
|
+
// Attempting to pass a non-Tagged type to UnwrapTagged will raise a type error.
|
|
599
|
+
// @ts-expect-error
|
|
600
|
+
type WontWork = UnwrapTagged<string>;
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
@category Type
|
|
604
|
+
*/
|
|
605
|
+
type UnwrapTagged<TaggedType extends Tag<PropertyKey, any>> = RemoveAllTags<TaggedType>;
|
|
606
|
+
type RemoveAllTags<T> = T extends Tag<PropertyKey, any> ? { [ThisTag in keyof T[typeof tag]]: T extends Tagged<infer Type, ThisTag, T[typeof tag][ThisTag]> ? RemoveAllTags<Type> : never; }[keyof T[typeof tag]] : T;
|
|
607
|
+
/**
|
|
608
|
+
Returns a boolean for whether the given type is a `string` [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types).
|
|
609
|
+
|
|
610
|
+
Useful for:
|
|
611
|
+
- providing strongly-typed string manipulation functions
|
|
612
|
+
- constraining strings to be a string literal
|
|
613
|
+
- type utilities, such as when constructing parsers and ASTs
|
|
614
|
+
|
|
615
|
+
The implementation of this type is inspired by the trick mentioned in this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
616
|
+
|
|
617
|
+
@example
|
|
618
|
+
```
|
|
619
|
+
import type {IsStringLiteral} from 'type-fest';
|
|
620
|
+
|
|
621
|
+
type CapitalizedString<T extends string> = IsStringLiteral<T> extends true ? Capitalize<T> : string;
|
|
622
|
+
|
|
623
|
+
// https://github.com/yankeeinlondon/native-dash/blob/master/src/capitalize.ts
|
|
624
|
+
function capitalize<T extends Readonly<string>>(input: T): CapitalizedString<T> {
|
|
625
|
+
return (input.slice(0, 1).toUpperCase() + input.slice(1)) as CapitalizedString<T>;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const output = capitalize('hello, world!');
|
|
629
|
+
//=> 'Hello, world!'
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
@example
|
|
633
|
+
```
|
|
634
|
+
// String types with infinite set of possible values return `false`.
|
|
635
|
+
|
|
636
|
+
import type {IsStringLiteral} from 'type-fest';
|
|
637
|
+
|
|
638
|
+
type AllUppercaseStrings = IsStringLiteral<Uppercase<string>>;
|
|
639
|
+
//=> false
|
|
640
|
+
|
|
641
|
+
type StringsStartingWithOn = IsStringLiteral<`on${string}`>;
|
|
642
|
+
//=> false
|
|
643
|
+
|
|
644
|
+
// This behaviour is particularly useful in string manipulation utilities, as infinite string types often require separate handling.
|
|
645
|
+
|
|
646
|
+
type Length<S extends string, Counter extends never[] = []> =
|
|
647
|
+
IsStringLiteral<S> extends false
|
|
648
|
+
? number // return `number` for infinite string types
|
|
649
|
+
: S extends `${string}${infer Tail}`
|
|
650
|
+
? Length<Tail, [...Counter, never]>
|
|
651
|
+
: Counter['length'];
|
|
652
|
+
|
|
653
|
+
type L1 = Length<Lowercase<string>>;
|
|
654
|
+
//=> number
|
|
655
|
+
|
|
656
|
+
type L2 = Length<`${number}`>;
|
|
657
|
+
//=> number
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
@category Type Guard
|
|
661
|
+
@category Utilities
|
|
662
|
+
*/
|
|
663
|
+
type IsStringLiteral<S> = IfNotAnyOrNever<S, {
|
|
664
|
+
ifNot: _IsStringLiteral<CollapseLiterals<S extends TagContainer<any> ? UnwrapTagged<S> : S>>;
|
|
665
|
+
ifAny: false;
|
|
666
|
+
ifNever: false;
|
|
667
|
+
}>;
|
|
668
|
+
type _IsStringLiteral<S> =
|
|
669
|
+
// If `T` is an infinite string type (e.g., `on${string}`), `Record<T, never>` produces an index signature,
|
|
670
|
+
// and since `{}` extends index signatures, the result becomes `false`.
|
|
671
|
+
S extends string ? {} extends Record<S, never> ? false : true : false;
|
|
672
|
+
/**
|
|
673
|
+
Create a tuple type of the specified length with elements of the specified type.
|
|
674
|
+
|
|
675
|
+
@example
|
|
676
|
+
```
|
|
677
|
+
import type {TupleOf} from 'type-fest';
|
|
678
|
+
|
|
679
|
+
type RGB = TupleOf<3, number>;
|
|
680
|
+
//=> [number, number, number]
|
|
681
|
+
|
|
682
|
+
type Line = TupleOf<2, {x: number; y: number}>;
|
|
683
|
+
//=> [{x: number; y: number}, {x: number; y: number}]
|
|
684
|
+
|
|
685
|
+
type TicTacToeBoard = TupleOf<3, TupleOf<3, 'X' | 'O' | null>>;
|
|
686
|
+
//=> [['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null], ['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null], ['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null]]
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
@example
|
|
690
|
+
```
|
|
691
|
+
import type {TupleOf} from 'type-fest';
|
|
692
|
+
|
|
693
|
+
type Range<Start extends number, End extends number> = Exclude<keyof TupleOf<End>, keyof TupleOf<Start>>;
|
|
694
|
+
|
|
695
|
+
type ZeroToFour = Range<0, 5>;
|
|
696
|
+
//=> '0' | '1' | '2' | '3' | '4'
|
|
697
|
+
|
|
698
|
+
type ThreeToEight = Range<3, 9>;
|
|
699
|
+
//=> '3' | '4' | '5' | '6' | '7' | '8'
|
|
700
|
+
```
|
|
701
|
+
|
|
702
|
+
Note: If the specified length is the non-literal `number` type, the result will not be a tuple but a regular array.
|
|
703
|
+
|
|
704
|
+
@example
|
|
705
|
+
```
|
|
706
|
+
import type {TupleOf} from 'type-fest';
|
|
707
|
+
|
|
708
|
+
type StringArray = TupleOf<number, string>;
|
|
709
|
+
//=> string[]
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
Note: If the type for elements is not specified, it will default to `unknown`.
|
|
713
|
+
|
|
714
|
+
@example
|
|
715
|
+
```
|
|
716
|
+
import type {TupleOf} from 'type-fest';
|
|
717
|
+
|
|
718
|
+
type UnknownTriplet = TupleOf<3>;
|
|
719
|
+
//=> [unknown, unknown, unknown]
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
Note: If the specified length is negative, the result will be an empty tuple.
|
|
723
|
+
|
|
724
|
+
@example
|
|
725
|
+
```
|
|
726
|
+
import type {TupleOf} from 'type-fest';
|
|
727
|
+
|
|
728
|
+
type EmptyTuple = TupleOf<-3, string>;
|
|
729
|
+
//=> []
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
Note: If the specified length has a decimal part, the decimal part will be ignored.
|
|
733
|
+
|
|
734
|
+
@example
|
|
735
|
+
```
|
|
736
|
+
import type {TupleOf} from 'type-fest';
|
|
737
|
+
|
|
738
|
+
type DecimalLength = TupleOf<3.5, string>;
|
|
739
|
+
//=> [string, string, string]
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
Note: If you need a readonly tuple, simply wrap this type with `Readonly`, for example, to create `readonly [number, number, number]` use `Readonly<TupleOf<3, number>>`.
|
|
743
|
+
|
|
744
|
+
@category Array
|
|
745
|
+
*/
|
|
746
|
+
type TupleOf<Length extends number, Fill = unknown> = IfNotAnyOrNever<Length, {
|
|
747
|
+
ifNot: _TupleOf<If<IsNegative<Length>, 0, Length>, Fill>;
|
|
748
|
+
ifAny: Fill[];
|
|
749
|
+
ifNever: [];
|
|
750
|
+
}>;
|
|
751
|
+
type _TupleOf<Length extends number, Fill> = number extends Length ? Fill[] : BuildTupleDigitByDigit<`${Length}`, Fill>;
|
|
752
|
+
type BuildTupleDigitByDigit<Length extends string, Fill, Accumulator extends UnknownArray = []> = Length extends `${infer First extends DigitCharacter}${infer Rest}` ? BuildTupleDigitByDigit<Rest, Fill, [...RepeatTupleTenTimes<Accumulator>, ...DigitTupleOf<First, Fill>]> : Accumulator;
|
|
753
|
+
type RepeatTupleTenTimes<Tuple extends UnknownArray> = [...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple, ...Tuple];
|
|
754
|
+
type DigitTupleOf<Digit extends DigitCharacter, Fill> = [[], [Fill], [Fill, Fill], [Fill, Fill, Fill], [Fill, Fill, Fill, Fill], [Fill, Fill, Fill, Fill, Fill], [Fill, Fill, Fill, Fill, Fill, Fill], [Fill, Fill, Fill, Fill, Fill, Fill, Fill], [Fill, Fill, Fill, Fill, Fill, Fill, Fill, Fill], [Fill, Fill, Fill, Fill, Fill, Fill, Fill, Fill, Fill]][Digit];
|
|
755
|
+
/**
|
|
756
|
+
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.
|
|
757
|
+
|
|
758
|
+
@example
|
|
759
|
+
```
|
|
760
|
+
import type {Simplify} from 'type-fest';
|
|
761
|
+
|
|
762
|
+
type PositionProps = {
|
|
763
|
+
top: number;
|
|
764
|
+
left: number;
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
type SizeProps = {
|
|
768
|
+
width: number;
|
|
769
|
+
height: number;
|
|
770
|
+
};
|
|
771
|
+
|
|
772
|
+
// In your editor, hovering over `Props` will show a flattened object with all the properties.
|
|
773
|
+
type Props = Simplify<PositionProps & SizeProps>;
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
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.
|
|
777
|
+
|
|
778
|
+
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`.
|
|
779
|
+
|
|
780
|
+
@example
|
|
781
|
+
```
|
|
782
|
+
import type {Simplify} from 'type-fest';
|
|
783
|
+
|
|
784
|
+
interface SomeInterface {
|
|
785
|
+
foo: number;
|
|
786
|
+
bar?: string;
|
|
787
|
+
baz: number | undefined;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
type SomeType = {
|
|
791
|
+
foo: number;
|
|
792
|
+
bar?: string;
|
|
793
|
+
baz: number | undefined;
|
|
794
|
+
};
|
|
795
|
+
|
|
796
|
+
const literal = {foo: 123, bar: 'hello', baz: 456};
|
|
797
|
+
const someType: SomeType = literal;
|
|
798
|
+
const someInterface: SomeInterface = literal;
|
|
799
|
+
|
|
800
|
+
declare function fn(object: Record<string, unknown>): void;
|
|
801
|
+
|
|
802
|
+
fn(literal); // Good: literal object type is sealed
|
|
803
|
+
fn(someType); // Good: type is sealed
|
|
804
|
+
// @ts-expect-error
|
|
805
|
+
fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
|
|
806
|
+
fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
|
|
807
|
+
```
|
|
808
|
+
|
|
809
|
+
@link https://github.com/microsoft/TypeScript/issues/15300
|
|
810
|
+
@see {@link SimplifyDeep}
|
|
811
|
+
@category Object
|
|
812
|
+
*/
|
|
813
|
+
type Simplify<T> = { [KeyType in keyof T]: T[KeyType]; } & {};
|
|
814
|
+
/**
|
|
815
|
+
Returns a boolean for whether the two given types are equal.
|
|
816
|
+
|
|
817
|
+
@link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
|
|
818
|
+
@link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
|
|
819
|
+
|
|
820
|
+
Use-cases:
|
|
821
|
+
- If you want to make a conditional branch based on the result of a comparison of two types.
|
|
822
|
+
|
|
823
|
+
@example
|
|
824
|
+
```
|
|
825
|
+
import type {IsEqual} from 'type-fest';
|
|
826
|
+
|
|
827
|
+
// This type returns a boolean for whether the given array includes the given item.
|
|
828
|
+
// `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
|
|
829
|
+
type Includes<Value extends readonly any[], Item> =
|
|
830
|
+
Value extends readonly [Value[0], ...infer rest]
|
|
831
|
+
? IsEqual<Value[0], Item> extends true
|
|
832
|
+
? true
|
|
833
|
+
: Includes<rest, Item>
|
|
834
|
+
: false;
|
|
835
|
+
```
|
|
836
|
+
|
|
837
|
+
@category Type Guard
|
|
838
|
+
@category Utilities
|
|
839
|
+
*/
|
|
840
|
+
type IsEqual<A, B> = [A] extends [B] ? [B] extends [A] ? _IsEqual<A, B> : false : false;
|
|
841
|
+
// This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`.
|
|
842
|
+
type _IsEqual<A, B> = (<G>() => G extends A & G | G ? 1 : 2) extends (<G>() => G extends B & G | G ? 1 : 2) ? true : false;
|
|
843
|
+
/**
|
|
844
|
+
Omit any index signatures from the given object type, leaving only explicitly defined properties.
|
|
845
|
+
|
|
846
|
+
This is the counterpart of `PickIndexSignature`.
|
|
847
|
+
|
|
848
|
+
Use-cases:
|
|
849
|
+
- Remove overly permissive signatures from third-party types.
|
|
850
|
+
|
|
851
|
+
This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
852
|
+
|
|
853
|
+
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>`.
|
|
854
|
+
|
|
855
|
+
(The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
|
|
856
|
+
|
|
857
|
+
```
|
|
858
|
+
const indexed: Record<string, unknown> = {}; // Allowed
|
|
859
|
+
|
|
860
|
+
// @ts-expect-error
|
|
861
|
+
const keyed: Record<'foo', unknown> = {}; // Error
|
|
862
|
+
// TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
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:
|
|
866
|
+
|
|
867
|
+
```
|
|
868
|
+
type Indexed = {} extends Record<string, unknown>
|
|
869
|
+
? '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
870
|
+
: '❌ `{}` is NOT assignable to `Record<string, unknown>`';
|
|
871
|
+
|
|
872
|
+
type IndexedResult = Indexed;
|
|
873
|
+
//=> '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
874
|
+
|
|
875
|
+
type Keyed = {} extends Record<'foo' | 'bar', unknown>
|
|
876
|
+
? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', unknown>`'
|
|
877
|
+
: '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`';
|
|
878
|
+
|
|
879
|
+
type KeyedResult = Keyed;
|
|
880
|
+
//=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`'
|
|
881
|
+
```
|
|
882
|
+
|
|
883
|
+
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`...
|
|
884
|
+
|
|
885
|
+
```
|
|
886
|
+
type OmitIndexSignature<ObjectType> = {
|
|
887
|
+
[KeyType in keyof ObjectType // Map each key of `ObjectType`...
|
|
888
|
+
]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
|
|
889
|
+
};
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
|
|
893
|
+
|
|
894
|
+
```
|
|
895
|
+
type OmitIndexSignature<ObjectType> = {
|
|
896
|
+
[KeyType in keyof ObjectType
|
|
897
|
+
// Is `{}` assignable to `Record<KeyType, unknown>`?
|
|
898
|
+
as {} extends Record<KeyType, unknown>
|
|
899
|
+
? never // ✅ `{}` is assignable to `Record<KeyType, unknown>`
|
|
900
|
+
: KeyType // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
|
|
901
|
+
]: ObjectType[KeyType];
|
|
902
|
+
};
|
|
903
|
+
```
|
|
904
|
+
|
|
905
|
+
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.
|
|
906
|
+
|
|
907
|
+
@example
|
|
908
|
+
```
|
|
909
|
+
import type {OmitIndexSignature} from 'type-fest';
|
|
910
|
+
|
|
911
|
+
type Example = {
|
|
912
|
+
// These index signatures will be removed.
|
|
913
|
+
[x: string]: any;
|
|
914
|
+
[x: number]: any;
|
|
915
|
+
[x: symbol]: any;
|
|
916
|
+
[x: `head-${string}`]: string;
|
|
917
|
+
[x: `${string}-tail`]: string;
|
|
918
|
+
[x: `head-${string}-tail`]: string;
|
|
919
|
+
[x: `${bigint}`]: string;
|
|
920
|
+
[x: `embedded-${number}`]: string;
|
|
921
|
+
|
|
922
|
+
// These explicitly defined keys will remain.
|
|
923
|
+
foo: 'bar';
|
|
924
|
+
qux?: 'baz';
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
|
|
928
|
+
//=> {foo: 'bar'; qux?: 'baz'}
|
|
929
|
+
```
|
|
930
|
+
|
|
931
|
+
@see {@link PickIndexSignature}
|
|
932
|
+
@category Object
|
|
933
|
+
*/
|
|
934
|
+
type OmitIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? never : KeyType]: ObjectType[KeyType]; };
|
|
935
|
+
/**
|
|
936
|
+
Pick only index signatures from the given object type, leaving out all explicitly defined properties.
|
|
937
|
+
|
|
938
|
+
This is the counterpart of `OmitIndexSignature`.
|
|
939
|
+
|
|
940
|
+
@example
|
|
941
|
+
```
|
|
942
|
+
import type {PickIndexSignature} from 'type-fest';
|
|
943
|
+
|
|
944
|
+
declare const symbolKey: unique symbol;
|
|
945
|
+
|
|
946
|
+
type Example = {
|
|
947
|
+
// These index signatures will remain.
|
|
948
|
+
[x: string]: unknown;
|
|
949
|
+
[x: number]: unknown;
|
|
950
|
+
[x: symbol]: unknown;
|
|
951
|
+
[x: `head-${string}`]: string;
|
|
952
|
+
[x: `${string}-tail`]: string;
|
|
953
|
+
[x: `head-${string}-tail`]: string;
|
|
954
|
+
[x: `${bigint}`]: string;
|
|
955
|
+
[x: `embedded-${number}`]: string;
|
|
956
|
+
|
|
957
|
+
// These explicitly defined keys will be removed.
|
|
958
|
+
['kebab-case-key']: string;
|
|
959
|
+
[symbolKey]: string;
|
|
960
|
+
foo: 'bar';
|
|
961
|
+
qux?: 'baz';
|
|
962
|
+
};
|
|
963
|
+
|
|
964
|
+
type ExampleIndexSignature = PickIndexSignature<Example>;
|
|
965
|
+
// {
|
|
966
|
+
// [x: string]: unknown;
|
|
967
|
+
// [x: number]: unknown;
|
|
968
|
+
// [x: symbol]: unknown;
|
|
969
|
+
// [x: `head-${string}`]: string;
|
|
970
|
+
// [x: `${string}-tail`]: string;
|
|
971
|
+
// [x: `head-${string}-tail`]: string;
|
|
972
|
+
// [x: `${bigint}`]: string;
|
|
973
|
+
// [x: `embedded-${number}`]: string;
|
|
974
|
+
// }
|
|
975
|
+
```
|
|
976
|
+
|
|
977
|
+
@see {@link OmitIndexSignature}
|
|
978
|
+
@category Object
|
|
979
|
+
*/
|
|
980
|
+
type PickIndexSignature<ObjectType> = { [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown> ? KeyType : never]: ObjectType[KeyType]; };
|
|
981
|
+
// Merges two objects without worrying about index signatures.
|
|
982
|
+
type SimpleMerge<Destination, Source> = Simplify<{ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key]; } & Source>;
|
|
983
|
+
/**
|
|
984
|
+
Merge two types into a new type. Keys of the second type overrides keys of the first type.
|
|
985
|
+
|
|
986
|
+
This is different from the TypeScript `&` (intersection) operator. With `&`, conflicting property types are intersected, which often results in `never`. For example, `{a: string} & {a: number}` makes `a` become `string & number`, which resolves to `never`. With `Merge`, the second type's keys cleanly override the first, so `Merge<{a: string}, {a: number}>` gives `{a: number}` as expected. `Merge` also produces a flattened type (via `Simplify`), making it more readable in IDE tooltips compared to `A & B`.
|
|
987
|
+
|
|
988
|
+
@example
|
|
989
|
+
```
|
|
990
|
+
import type {Merge} from 'type-fest';
|
|
991
|
+
|
|
992
|
+
type Foo = {
|
|
993
|
+
a: string;
|
|
994
|
+
b: number;
|
|
995
|
+
};
|
|
996
|
+
|
|
997
|
+
type Bar = {
|
|
998
|
+
a: number; // Conflicts with Foo['a']
|
|
999
|
+
c: boolean;
|
|
1000
|
+
};
|
|
1001
|
+
|
|
1002
|
+
// With `&`, `a` becomes `string & number` which is `never`. Not what you want.
|
|
1003
|
+
type WithIntersection = (Foo & Bar)['a'];
|
|
1004
|
+
//=> never
|
|
1005
|
+
|
|
1006
|
+
// With `Merge`, `a` is cleanly overridden to `number`.
|
|
1007
|
+
type WithMerge = Merge<Foo, Bar>['a'];
|
|
1008
|
+
//=> number
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
@example
|
|
1012
|
+
```
|
|
1013
|
+
import type {Merge} from 'type-fest';
|
|
1014
|
+
|
|
1015
|
+
type Foo = {
|
|
1016
|
+
[x: string]: unknown;
|
|
1017
|
+
[x: number]: unknown;
|
|
1018
|
+
foo: string;
|
|
1019
|
+
bar: symbol;
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
type Bar = {
|
|
1023
|
+
[x: number]: number;
|
|
1024
|
+
[x: symbol]: unknown;
|
|
1025
|
+
bar: Date;
|
|
1026
|
+
baz: boolean;
|
|
1027
|
+
};
|
|
1028
|
+
|
|
1029
|
+
export type FooBar = Merge<Foo, Bar>;
|
|
1030
|
+
//=> {
|
|
1031
|
+
// [x: string]: unknown;
|
|
1032
|
+
// [x: number]: number;
|
|
1033
|
+
// [x: symbol]: unknown;
|
|
1034
|
+
// foo: string;
|
|
1035
|
+
// bar: Date;
|
|
1036
|
+
// baz: boolean;
|
|
1037
|
+
// }
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
Note: If you want a merge type that more accurately reflects the runtime behavior of object spread or `Object.assign`, refer to the {@link ObjectMerge} type.
|
|
1041
|
+
|
|
1042
|
+
@see {@link ObjectMerge}
|
|
1043
|
+
@category Object
|
|
1044
|
+
*/
|
|
1045
|
+
type Merge<Destination, Source> = Destination extends unknown // For distributing `Destination`
|
|
1046
|
+
? Source extends unknown // For distributing `Source`
|
|
1047
|
+
? If<IsEqual<Destination, Source>, Destination, _Merge<Destination, Source>> : never // Should never happen
|
|
1048
|
+
: never; // Should never happen
|
|
1049
|
+
type _Merge<Destination, Source> = Simplify<SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>> & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>>;
|
|
1050
|
+
/**
|
|
1051
|
+
Converts a numeric string to a number.
|
|
1052
|
+
|
|
1053
|
+
@example
|
|
1054
|
+
```
|
|
1055
|
+
import type {StringToNumber} from 'type-fest';
|
|
1056
|
+
|
|
1057
|
+
type PositiveInteger = StringToNumber<'1234'>;
|
|
1058
|
+
//=> 1234
|
|
1059
|
+
|
|
1060
|
+
type NegativeInteger = StringToNumber<'-1234'>;
|
|
1061
|
+
//=> -1234
|
|
1062
|
+
|
|
1063
|
+
type PositiveFloat = StringToNumber<'1234.56'>;
|
|
1064
|
+
//=> 1234.56
|
|
1065
|
+
|
|
1066
|
+
type NegativeFloat = StringToNumber<'-1234.56'>;
|
|
1067
|
+
//=> -1234.56
|
|
1068
|
+
|
|
1069
|
+
type PositiveInfinity = StringToNumber<'Infinity'>;
|
|
1070
|
+
//=> Infinity
|
|
1071
|
+
|
|
1072
|
+
type NegativeInfinity = StringToNumber<'-Infinity'>;
|
|
1073
|
+
//=> -Infinity
|
|
1074
|
+
```
|
|
1075
|
+
|
|
1076
|
+
Note: Some strings, such as `'1.50'`, `'0b10'`, or `'12_345'`, may look like they can be converted to numbers, but they don't actually have corresponding numeric literals. So, in such cases, this type produces `never`. See [type-fest#1446](https://github.com/sindresorhus/type-fest/pull/1446) for more details.
|
|
1077
|
+
|
|
1078
|
+
@example
|
|
1079
|
+
```
|
|
1080
|
+
import type {StringToNumber} from 'type-fest';
|
|
1081
|
+
|
|
1082
|
+
type FractionalsEndingInZero = StringToNumber<'1.50'>;
|
|
1083
|
+
//=> never
|
|
1084
|
+
|
|
1085
|
+
type NonDecimalBases = StringToNumber<'0b10' | '0o10' | '0x10'>;
|
|
1086
|
+
//=> never
|
|
1087
|
+
|
|
1088
|
+
type NumericSeparators = StringToNumber<'12_345'>;
|
|
1089
|
+
//=> never
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
@category String
|
|
1093
|
+
@category Numeric
|
|
1094
|
+
@category Template literal
|
|
1095
|
+
*/
|
|
1096
|
+
type StringToNumber<S extends string> = IfNotAnyOrNever<S, {
|
|
1097
|
+
ifNot: _StringToNumber<S>;
|
|
1098
|
+
ifAny: number;
|
|
1099
|
+
}>;
|
|
1100
|
+
type _StringToNumber<S extends string> = S extends `${infer N extends number}` ? number extends N ? `${number}` extends S ? N : never : N : string extends S ? number : S extends 'Infinity' ? PositiveInfinity : S extends '-Infinity' ? NegativeInfinity : never;
|
|
1101
|
+
/**
|
|
1102
|
+
Merges user specified options with default options.
|
|
1103
|
+
|
|
1104
|
+
@example
|
|
1105
|
+
```
|
|
1106
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1107
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
1108
|
+
type SpecifiedOptions = {leavesOnly: true};
|
|
1109
|
+
|
|
1110
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1111
|
+
//=> {maxRecursionDepth: 10; leavesOnly: true}
|
|
1112
|
+
```
|
|
1113
|
+
|
|
1114
|
+
@example
|
|
1115
|
+
```
|
|
1116
|
+
// Complains if default values are not provided for optional options
|
|
1117
|
+
|
|
1118
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1119
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10};
|
|
1120
|
+
type SpecifiedOptions = {};
|
|
1121
|
+
|
|
1122
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1123
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
1124
|
+
// Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
|
|
1125
|
+
```
|
|
1126
|
+
|
|
1127
|
+
@example
|
|
1128
|
+
```
|
|
1129
|
+
// Complains if an option's default type does not conform to the expected type
|
|
1130
|
+
|
|
1131
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1132
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
|
|
1133
|
+
type SpecifiedOptions = {};
|
|
1134
|
+
|
|
1135
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1136
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
1137
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
1138
|
+
```
|
|
1139
|
+
|
|
1140
|
+
@example
|
|
1141
|
+
```
|
|
1142
|
+
// Complains if an option's specified type does not conform to the expected type
|
|
1143
|
+
|
|
1144
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1145
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
1146
|
+
type SpecifiedOptions = {leavesOnly: 'yes'};
|
|
1147
|
+
|
|
1148
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1149
|
+
// ~~~~~~~~~~~~~~~~
|
|
1150
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
1151
|
+
```
|
|
1152
|
+
*/
|
|
1153
|
+
type ApplyDefaultOptions<Options extends object, Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>, SpecifiedOptions extends Options> = _ApplyDefaultOptions<Options, Defaults, SpecifiedOptions> extends (infer Result extends Required<Options> // `extends Required<Options>` ensures that `ApplyDefaultOptions<SomeOption, ...>` is always assignable to `Required<SomeOption>`
|
|
1154
|
+
) ? Result : never;
|
|
1155
|
+
type _ApplyDefaultOptions<Options, Defaults, SpecifiedOptions> = If<IsAny<SpecifiedOptions>, Defaults, If<IsNever<SpecifiedOptions>, Defaults, Merge<Defaults, { [Key in keyof SpecifiedOptions as undefined extends Required<Options>[Key & keyof Options] ? Key : undefined extends SpecifiedOptions[Key] ? never : Key]: SpecifiedOptions[Key]; }>>>;
|
|
1156
|
+
/**
|
|
1157
|
+
Collapses literal types in a union into their corresponding primitive types, when possible. For example, `CollapseLiterals<'foo' | 'bar' | (string & {})>` returns `string`.
|
|
1158
|
+
|
|
1159
|
+
Note: This doesn't collapse literals within tagged types. For example, `CollapseLiterals<Tagged<'foo' | (string & {}), 'Tag'>>` returns `("foo" & Tag<"Tag", never>) | (string & Tag<"Tag", never>)` and not `string & Tag<"Tag", never>`.
|
|
1160
|
+
|
|
1161
|
+
Use-case: For collapsing unions created using {@link LiteralUnion}.
|
|
1162
|
+
|
|
1163
|
+
@example
|
|
1164
|
+
```
|
|
1165
|
+
import type {LiteralUnion} from 'type-fest';
|
|
1166
|
+
|
|
1167
|
+
type A = CollapseLiterals<'foo' | 'bar' | (string & {})>;
|
|
1168
|
+
//=> string
|
|
1169
|
+
|
|
1170
|
+
type B = CollapseLiterals<LiteralUnion<1 | 2 | 3, number>>;
|
|
1171
|
+
//=> number
|
|
1172
|
+
|
|
1173
|
+
type C = CollapseLiterals<LiteralUnion<'onClick' | 'onChange', `on${string}`>>;
|
|
1174
|
+
//=> `on${string}`
|
|
1175
|
+
|
|
1176
|
+
type D = CollapseLiterals<'click' | 'change' | (`on${string}` & {})>;
|
|
1177
|
+
//=> 'click' | 'change' | `on${string}`
|
|
1178
|
+
|
|
1179
|
+
type E = CollapseLiterals<LiteralUnion<'foo' | 'bar', string> | null | undefined>;
|
|
1180
|
+
//=> string | null | undefined
|
|
1181
|
+
```
|
|
1182
|
+
*/
|
|
1183
|
+
type CollapseLiterals<T> = {} extends T ? T : T extends (infer U) & {} ? U : T;
|
|
1184
|
+
/**
|
|
1185
|
+
@see {@link SomeExtend}
|
|
1186
|
+
*/
|
|
1187
|
+
type SomeExtendOptions = {
|
|
1188
|
+
/**
|
|
1189
|
+
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
1190
|
+
|
|
1191
|
+
- 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`).
|
|
1192
|
+
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
1193
|
+
|
|
1194
|
+
@default true
|
|
1195
|
+
|
|
1196
|
+
@example
|
|
1197
|
+
```
|
|
1198
|
+
import type {SomeExtend} from 'type-fest';
|
|
1199
|
+
|
|
1200
|
+
type A = SomeExtend<[1, 2, never], string, {strictNever: true}>;
|
|
1201
|
+
//=> false
|
|
1202
|
+
|
|
1203
|
+
type B = SomeExtend<[1, 2, never], string, {strictNever: false}>;
|
|
1204
|
+
//=> true
|
|
1205
|
+
|
|
1206
|
+
type C = SomeExtend<[1, never], never, {strictNever: true}>;
|
|
1207
|
+
//=> true
|
|
1208
|
+
|
|
1209
|
+
type D = SomeExtend<[1, never], never, {strictNever: false}>;
|
|
1210
|
+
//=> true
|
|
1211
|
+
|
|
1212
|
+
type E = SomeExtend<[never], any, {strictNever: true}>;
|
|
1213
|
+
//=> true
|
|
1214
|
+
|
|
1215
|
+
type F = SomeExtend<[never], any, {strictNever: false}>;
|
|
1216
|
+
//=> true
|
|
1217
|
+
```
|
|
1218
|
+
*/
|
|
1219
|
+
strictNever?: boolean;
|
|
1220
|
+
};
|
|
1221
|
+
type DefaultSomeExtendOptions = {
|
|
1222
|
+
strictNever: true;
|
|
1223
|
+
};
|
|
1224
|
+
/**
|
|
1225
|
+
Returns a boolean for whether some element in an array type extends another type.
|
|
1226
|
+
|
|
1227
|
+
@example
|
|
1228
|
+
```
|
|
1229
|
+
import type {SomeExtend} from 'type-fest';
|
|
1230
|
+
|
|
1231
|
+
type A = SomeExtend<['1', '2', 3], number>;
|
|
1232
|
+
//=> true
|
|
1233
|
+
|
|
1234
|
+
type B = SomeExtend<[1, 2, 3], string>;
|
|
1235
|
+
//=> false
|
|
1236
|
+
|
|
1237
|
+
type C = SomeExtend<[string, number | string], number>;
|
|
1238
|
+
//=> boolean
|
|
1239
|
+
|
|
1240
|
+
type D = SomeExtend<[true, boolean, true], false>;
|
|
1241
|
+
//=> boolean
|
|
1242
|
+
```
|
|
1243
|
+
|
|
1244
|
+
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.
|
|
1245
|
+
|
|
1246
|
+
```
|
|
1247
|
+
// @exactOptionalPropertyTypes: true
|
|
1248
|
+
import type {SomeExtend} from 'type-fest';
|
|
1249
|
+
|
|
1250
|
+
type A = SomeExtend<[1?, 2?, '3'?], string>;
|
|
1251
|
+
//=> true
|
|
1252
|
+
```
|
|
1253
|
+
|
|
1254
|
+
```
|
|
1255
|
+
// @exactOptionalPropertyTypes: false
|
|
1256
|
+
import type {SomeExtend} from 'type-fest';
|
|
1257
|
+
|
|
1258
|
+
type A = SomeExtend<[1?, 2?, '3'?], string>;
|
|
1259
|
+
//=> boolean
|
|
1260
|
+
|
|
1261
|
+
type B = SomeExtend<[1?, 2?, '3'?], string | undefined>;
|
|
1262
|
+
//=> true
|
|
1263
|
+
```
|
|
1264
|
+
|
|
1265
|
+
@see {@link SomeExtendOptions}
|
|
1266
|
+
|
|
1267
|
+
@category Utilities
|
|
1268
|
+
@category Array
|
|
1269
|
+
*/
|
|
1270
|
+
type SomeExtend<TArray extends UnknownArray, Type, Options extends SomeExtendOptions = {}> = _SomeExtend<CollapseRestElement<TArray>, Type, ApplyDefaultOptions<SomeExtendOptions, DefaultSomeExtendOptions, Options>>;
|
|
1271
|
+
type _SomeExtend<TArray extends UnknownArray, Type, Options extends Required<SomeExtendOptions>> = IfNotAnyOrNever<TArray, {
|
|
1272
|
+
ifNot: TArray extends readonly [infer First, ...infer Rest] ? IsNever<First> extends true ? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true ?
|
|
1273
|
+
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, return `true`.
|
|
1274
|
+
true : _SomeExtend<Rest, Type, Options> : First extends Type ? true : _SomeExtend<Rest, Type, Options> : false;
|
|
1275
|
+
ifAny: false;
|
|
1276
|
+
ifNever: false;
|
|
1277
|
+
}>;
|
|
1278
|
+
/**
|
|
1279
|
+
Returns a boolean for whether any of the given elements is `true`.
|
|
1280
|
+
|
|
1281
|
+
Use-cases:
|
|
1282
|
+
- Check if at least one condition in a list of booleans is met.
|
|
1283
|
+
|
|
1284
|
+
@example
|
|
1285
|
+
```
|
|
1286
|
+
import type {OrAll} from 'type-fest';
|
|
1287
|
+
|
|
1288
|
+
type FFT = OrAll<[false, false, true]>;
|
|
1289
|
+
//=> true
|
|
1290
|
+
|
|
1291
|
+
type FFF = OrAll<[false, false, false]>;
|
|
1292
|
+
//=> false
|
|
1293
|
+
```
|
|
1294
|
+
|
|
1295
|
+
Note: When `boolean` is passed as an element, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1296
|
+
For example, `OrAll<[false, boolean]>` expands to `OrAll<[false, true]> | OrAll<[false, false]>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
1297
|
+
|
|
1298
|
+
@example
|
|
1299
|
+
```
|
|
1300
|
+
import type {OrAll} from 'type-fest';
|
|
1301
|
+
|
|
1302
|
+
type A = OrAll<[false, boolean]>;
|
|
1303
|
+
//=> boolean
|
|
1304
|
+
|
|
1305
|
+
type B = OrAll<[true, boolean]>;
|
|
1306
|
+
//=> true
|
|
1307
|
+
```
|
|
1308
|
+
|
|
1309
|
+
Note: If `never` is passed as an element, it is treated as `false` and the result is computed accordingly.
|
|
1310
|
+
|
|
1311
|
+
@example
|
|
1312
|
+
```
|
|
1313
|
+
import type {OrAll} from 'type-fest';
|
|
1314
|
+
|
|
1315
|
+
type A = OrAll<[never, never, true]>;
|
|
1316
|
+
//=> true
|
|
1317
|
+
|
|
1318
|
+
type B = OrAll<[never, never, false]>;
|
|
1319
|
+
//=> false
|
|
1320
|
+
|
|
1321
|
+
type C = OrAll<[never, never, never]>;
|
|
1322
|
+
//=> false
|
|
1323
|
+
|
|
1324
|
+
type D = OrAll<[never, never, boolean]>;
|
|
1325
|
+
//=> boolean
|
|
1326
|
+
```
|
|
1327
|
+
|
|
1328
|
+
Note: If `any` is passed as an element, it is treated as `boolean` and the result is computed accordingly.
|
|
1329
|
+
|
|
1330
|
+
@example
|
|
1331
|
+
```
|
|
1332
|
+
import type {OrAll} from 'type-fest';
|
|
1333
|
+
|
|
1334
|
+
type A = OrAll<[false, any]>;
|
|
1335
|
+
//=> boolean
|
|
1336
|
+
|
|
1337
|
+
type B = OrAll<[true, any]>;
|
|
1338
|
+
//=> true
|
|
1339
|
+
```
|
|
1340
|
+
|
|
1341
|
+
Note: `OrAll<[]>` evaluates to `false` because there are no `true` elements in an empty tuple. See [Wikipedia: Clause (logic) > Empty clauses](https://en.wikipedia.org/wiki/Clause_(logic)#Empty_clauses:~:text=The%20truth%20evaluation%20of%20an%20empty%20disjunctive%20clause%20is%20always%20false.).
|
|
1342
|
+
|
|
1343
|
+
@see {@link Or}
|
|
1344
|
+
@see {@link AndAll}
|
|
1345
|
+
*/
|
|
1346
|
+
type OrAll<T extends readonly boolean[]> = SomeExtend<T, true>;
|
|
1347
|
+
/**
|
|
1348
|
+
Returns a boolean for whether either of two given types is `true`.
|
|
1349
|
+
|
|
1350
|
+
Use-case: Constructing complex conditional types where at least one condition must be satisfied.
|
|
1351
|
+
|
|
1352
|
+
@example
|
|
1353
|
+
```
|
|
1354
|
+
import type {Or} from 'type-fest';
|
|
1355
|
+
|
|
1356
|
+
type TT = Or<true, true>;
|
|
1357
|
+
//=> true
|
|
1358
|
+
|
|
1359
|
+
type TF = Or<true, false>;
|
|
1360
|
+
//=> true
|
|
1361
|
+
|
|
1362
|
+
type FT = Or<false, true>;
|
|
1363
|
+
//=> true
|
|
1364
|
+
|
|
1365
|
+
type FF = Or<false, false>;
|
|
1366
|
+
//=> false
|
|
1367
|
+
```
|
|
1368
|
+
|
|
1369
|
+
Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1370
|
+
For example, `Or<false, boolean>` expands to `Or<false, true> | Or<false, false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
1371
|
+
|
|
1372
|
+
@example
|
|
1373
|
+
```
|
|
1374
|
+
import type {Or} from 'type-fest';
|
|
1375
|
+
|
|
1376
|
+
type A = Or<false, boolean>;
|
|
1377
|
+
//=> boolean
|
|
1378
|
+
|
|
1379
|
+
type B = Or<boolean, false>;
|
|
1380
|
+
//=> boolean
|
|
1381
|
+
|
|
1382
|
+
type C = Or<true, boolean>;
|
|
1383
|
+
//=> true
|
|
1384
|
+
|
|
1385
|
+
type D = Or<boolean, true>;
|
|
1386
|
+
//=> true
|
|
1387
|
+
|
|
1388
|
+
type E = Or<boolean, boolean>;
|
|
1389
|
+
//=> boolean
|
|
1390
|
+
```
|
|
1391
|
+
|
|
1392
|
+
Note: If `never` is passed as an argument, it is treated as `false` and the result is computed accordingly.
|
|
1393
|
+
|
|
1394
|
+
@example
|
|
1395
|
+
```
|
|
1396
|
+
import type {Or} from 'type-fest';
|
|
1397
|
+
|
|
1398
|
+
type A = Or<true, never>;
|
|
1399
|
+
//=> true
|
|
1400
|
+
|
|
1401
|
+
type B = Or<never, true>;
|
|
1402
|
+
//=> true
|
|
1403
|
+
|
|
1404
|
+
type C = Or<false, never>;
|
|
1405
|
+
//=> false
|
|
1406
|
+
|
|
1407
|
+
type D = Or<never, false>;
|
|
1408
|
+
//=> false
|
|
1409
|
+
|
|
1410
|
+
type E = Or<boolean, never>;
|
|
1411
|
+
//=> boolean
|
|
1412
|
+
|
|
1413
|
+
type F = Or<never, boolean>;
|
|
1414
|
+
//=> boolean
|
|
1415
|
+
|
|
1416
|
+
type G = Or<never, never>;
|
|
1417
|
+
//=> false
|
|
1418
|
+
```
|
|
1419
|
+
|
|
1420
|
+
@see {@link OrAll}
|
|
1421
|
+
@see {@link And}
|
|
1422
|
+
@see {@link Xor}
|
|
1423
|
+
*/
|
|
1424
|
+
type Or<A extends boolean, B extends boolean> = OrAll<[A, B]>;
|
|
1425
|
+
/**
|
|
1426
|
+
@see {@link StringToArray}
|
|
1427
|
+
*/
|
|
1428
|
+
type StringToArrayOptions = {
|
|
1429
|
+
/**
|
|
1430
|
+
When enabled, non-literal parts of the string (e.g., `string`, `Uppercase<string>`) are mapped as single elements instead of being mapped as a rest element.
|
|
1431
|
+
|
|
1432
|
+
Note: Enabling this option can produce misleading results that might not reflect the actual runtime behavior.
|
|
1433
|
+
For example, `StringToArray<string, {mapNonLiteralsDirectly: true}>` returns `[string]`, but at runtime, the string could be `'abc'` (which satisfies `string`), and converting it to an array would result in `['a', 'b', 'c']`, which doesn't satisfy `[string]`.
|
|
1434
|
+
|
|
1435
|
+
So, it is recommended to not enable this option unless you are aware of the implications.
|
|
1436
|
+
|
|
1437
|
+
@default false
|
|
1438
|
+
|
|
1439
|
+
@example
|
|
1440
|
+
```
|
|
1441
|
+
import type {StringToArray} from 'type-fest';
|
|
1442
|
+
|
|
1443
|
+
type A = StringToArray<string, {mapNonLiteralsDirectly: false}>;
|
|
1444
|
+
//=> string[]
|
|
1445
|
+
|
|
1446
|
+
type B = StringToArray<string, {mapNonLiteralsDirectly: true}>;
|
|
1447
|
+
//=> [string]
|
|
1448
|
+
|
|
1449
|
+
type C = StringToArray<`on${string}`, {mapNonLiteralsDirectly: false}>;
|
|
1450
|
+
//=> ['o', 'n', ...string[]]
|
|
1451
|
+
|
|
1452
|
+
type D = StringToArray<`on${string}`, {mapNonLiteralsDirectly: true}>;
|
|
1453
|
+
//=> ['o', 'n', string]
|
|
1454
|
+
|
|
1455
|
+
type E = StringToArray<`${string}xyz`, {mapNonLiteralsDirectly: false}>;
|
|
1456
|
+
//=> [...string[], 'x', 'y', 'z']
|
|
1457
|
+
|
|
1458
|
+
type F = StringToArray<`${string}xyz`, {mapNonLiteralsDirectly: true}>;
|
|
1459
|
+
//=> [string, 'x', 'y', 'z']
|
|
1460
|
+
```
|
|
1461
|
+
*/
|
|
1462
|
+
mapNonLiteralsDirectly?: boolean;
|
|
1463
|
+
};
|
|
1464
|
+
type DefaultStringToArrayOptions = {
|
|
1465
|
+
mapNonLiteralsDirectly: false;
|
|
1466
|
+
};
|
|
1467
|
+
/**
|
|
1468
|
+
Returns an array of the characters of the specified string.
|
|
1469
|
+
|
|
1470
|
+
@example
|
|
1471
|
+
```
|
|
1472
|
+
import type {StringToArray} from 'type-fest';
|
|
1473
|
+
|
|
1474
|
+
type A = StringToArray<'abcde'>;
|
|
1475
|
+
//=> ['a', 'b', 'c', 'd', 'e']
|
|
1476
|
+
|
|
1477
|
+
type B = StringToArray<''>;
|
|
1478
|
+
//=> []
|
|
1479
|
+
|
|
1480
|
+
type C = StringToArray<string>;
|
|
1481
|
+
//=> string[]
|
|
1482
|
+
|
|
1483
|
+
type D = StringToArray<`foo${string}bar`>;
|
|
1484
|
+
//=> ['f', 'o', 'o', ...string[], 'b', 'a', 'r']
|
|
1485
|
+
|
|
1486
|
+
type E = StringToArray<`foo${string}bar`, {mapNonLiteralsDirectly: true}>;
|
|
1487
|
+
//=> ['f', 'o', 'o', string, 'b', 'a', 'r']
|
|
1488
|
+
```
|
|
1489
|
+
|
|
1490
|
+
@see {@link StringToArrayOptions}
|
|
1491
|
+
|
|
1492
|
+
@category String
|
|
1493
|
+
*/
|
|
1494
|
+
type StringToArray<S extends string, Options extends StringToArrayOptions = {}> = IfNotAnyOrNever<S, {
|
|
1495
|
+
ifNot: _StringToArray<S, ApplyDefaultOptions<StringToArrayOptions, DefaultStringToArrayOptions, Options>>;
|
|
1496
|
+
ifAny: unknown[];
|
|
1497
|
+
}>;
|
|
1498
|
+
type _StringToArray<S extends string, Options extends Required<StringToArrayOptions>, Accumulator extends string[] = []> = S extends `${infer First}${infer Rest}` ? Or<IsStringLiteral<First>, Options['mapNonLiteralsDirectly']> extends true ? _StringToArray<Rest, Options, [...Accumulator, First]> : _StringToArray<Rest, Options, [...Accumulator, ...First[]]> : S extends '' ? Accumulator : Options['mapNonLiteralsDirectly'] extends true ? [...Accumulator, S] : [...Accumulator, ...S[]];
|
|
1499
|
+
/**
|
|
1500
|
+
Returns the length of the given string.
|
|
1501
|
+
|
|
1502
|
+
@example
|
|
1503
|
+
```
|
|
1504
|
+
import type {StringLength} from 'type-fest';
|
|
1505
|
+
|
|
1506
|
+
type A = StringLength<'abcde'>;
|
|
1507
|
+
//=> 5
|
|
1508
|
+
|
|
1509
|
+
type B = StringLength<'abcde' | 'fgh'>;
|
|
1510
|
+
//=> 3 | 5
|
|
1511
|
+
```
|
|
1512
|
+
|
|
1513
|
+
For non-literal strings, the result is `number` because the length of a non-literal string can be any number.
|
|
1514
|
+
|
|
1515
|
+
@example
|
|
1516
|
+
```
|
|
1517
|
+
import type {StringLength} from 'type-fest';
|
|
1518
|
+
|
|
1519
|
+
type A = StringLength<string>;
|
|
1520
|
+
//=> number
|
|
1521
|
+
|
|
1522
|
+
type B = StringLength<Uppercase<string>>;
|
|
1523
|
+
//=> number
|
|
1524
|
+
|
|
1525
|
+
type C = StringLength<`${string}abc`>;
|
|
1526
|
+
//=> number
|
|
1527
|
+
```
|
|
1528
|
+
|
|
1529
|
+
@category String
|
|
1530
|
+
@category Template literal
|
|
1531
|
+
*/
|
|
1532
|
+
type StringLength<S extends string> = StringToArray<S>['length'];
|
|
1533
|
+
/**
|
|
1534
|
+
Return a string representation of the given string or number.
|
|
1535
|
+
|
|
1536
|
+
Note: This type is not the return type of the `.toString()` function.
|
|
1537
|
+
*/
|
|
1538
|
+
type ToString<T> = T extends string | number ? `${T}` : never;
|
|
1539
|
+
/**
|
|
1540
|
+
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.
|
|
1541
|
+
|
|
1542
|
+
@example
|
|
1543
|
+
```
|
|
1544
|
+
type A = SameLengthPositiveNumericStringGt<'50', '10'>;
|
|
1545
|
+
//=> true
|
|
1546
|
+
|
|
1547
|
+
type B = SameLengthPositiveNumericStringGt<'10', '10'>;
|
|
1548
|
+
//=> false
|
|
1549
|
+
```
|
|
1550
|
+
*/
|
|
1551
|
+
type SameLengthPositiveNumericStringGt<A extends string, B extends string> = A extends `${infer FirstA}${infer RestA}` ? B extends `${infer FirstB}${infer RestB}` ? FirstA extends FirstB ? SameLengthPositiveNumericStringGt<RestA, RestB> : PositiveNumericCharacterGt<FirstA, FirstB> : never : false;
|
|
1552
|
+
type NumericString = '0123456789';
|
|
1553
|
+
/**
|
|
1554
|
+
Returns a boolean for whether `A` is greater than `B`, where `A` and `B` are both positive numeric strings.
|
|
1555
|
+
|
|
1556
|
+
@example
|
|
1557
|
+
```
|
|
1558
|
+
type A = PositiveNumericStringGt<'500', '1'>;
|
|
1559
|
+
//=> true
|
|
1560
|
+
|
|
1561
|
+
type B = PositiveNumericStringGt<'1', '1'>;
|
|
1562
|
+
//=> false
|
|
1563
|
+
|
|
1564
|
+
type C = PositiveNumericStringGt<'1', '500'>;
|
|
1565
|
+
//=> false
|
|
1566
|
+
```
|
|
1567
|
+
*/
|
|
1568
|
+
type PositiveNumericStringGt<A extends string, B extends string> = A extends B ? false : [TupleOf<StringLength<A>, 0>, TupleOf<StringLength<B>, 0>] extends (infer R extends [readonly unknown[], readonly unknown[]]) ? R[0] extends [...R[1], ...infer Remain extends readonly unknown[]] ? 0 extends Remain['length'] ? SameLengthPositiveNumericStringGt<A, B> : true : false : never;
|
|
1569
|
+
/**
|
|
1570
|
+
Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both positive numeric characters.
|
|
1571
|
+
|
|
1572
|
+
@example
|
|
1573
|
+
```
|
|
1574
|
+
type A = PositiveNumericCharacterGt<'5', '1'>;
|
|
1575
|
+
//=> true
|
|
1576
|
+
|
|
1577
|
+
type B = PositiveNumericCharacterGt<'1', '1'>;
|
|
1578
|
+
//=> false
|
|
1579
|
+
```
|
|
1580
|
+
*/
|
|
1581
|
+
type PositiveNumericCharacterGt<A extends string, B extends string> = NumericString extends `${infer HeadA}${A}${infer TailA}` ? NumericString extends `${infer HeadB}${B}${infer TailB}` ? HeadA extends `${HeadB}${infer _}${infer __}` ? true : false : never : never;
|
|
1582
|
+
/**
|
|
1583
|
+
Check whether the given type is a number or a number string.
|
|
1584
|
+
|
|
1585
|
+
Supports floating-point as a string.
|
|
1586
|
+
|
|
1587
|
+
@example
|
|
1588
|
+
```
|
|
1589
|
+
type A = IsNumberLike<'1'>;
|
|
1590
|
+
//=> true
|
|
1591
|
+
|
|
1592
|
+
type B = IsNumberLike<'-1.1'>;
|
|
1593
|
+
//=> true
|
|
1594
|
+
|
|
1595
|
+
type C = IsNumberLike<'5e-20'>;
|
|
1596
|
+
//=> true
|
|
1597
|
+
|
|
1598
|
+
type D = IsNumberLike<1>;
|
|
1599
|
+
//=> true
|
|
1600
|
+
|
|
1601
|
+
type E = IsNumberLike<'a'>;
|
|
1602
|
+
//=> false
|
|
1603
|
+
*/
|
|
1604
|
+
type IsNumberLike<N> = IfNotAnyOrNever<N, {
|
|
1605
|
+
ifNot: N extends number | `${number}` ? true : false;
|
|
1606
|
+
ifAny: boolean;
|
|
1607
|
+
ifNever: false;
|
|
1608
|
+
}>;
|
|
1609
|
+
/**
|
|
1610
|
+
Returns the number with reversed sign.
|
|
1611
|
+
|
|
1612
|
+
@example
|
|
1613
|
+
```
|
|
1614
|
+
type A = ReverseSign<-1>;
|
|
1615
|
+
//=> 1
|
|
1616
|
+
|
|
1617
|
+
type B = ReverseSign<1>;
|
|
1618
|
+
//=> -1
|
|
1619
|
+
|
|
1620
|
+
type C = ReverseSign<NegativeInfinity>;
|
|
1621
|
+
//=> PositiveInfinity
|
|
1622
|
+
|
|
1623
|
+
type D = ReverseSign<PositiveInfinity>;
|
|
1624
|
+
//=> NegativeInfinity
|
|
1625
|
+
```
|
|
1626
|
+
*/
|
|
1627
|
+
type ReverseSign<N extends number> =
|
|
1628
|
+
// Handle edge cases
|
|
1629
|
+
N extends 0 ? 0 : N extends PositiveInfinity ? NegativeInfinity : N extends NegativeInfinity ? PositiveInfinity :
|
|
1630
|
+
// Handle negative numbers
|
|
1631
|
+
`${N}` extends `-${infer P extends number}` ? P :
|
|
1632
|
+
// Handle positive numbers
|
|
1633
|
+
`-${N}` extends `${infer R extends number}` ? R : never;
|
|
1634
|
+
/**
|
|
1635
|
+
@see {@link AllExtend}
|
|
1636
|
+
*/
|
|
1637
|
+
type AllExtendOptions = {
|
|
1638
|
+
/**
|
|
1639
|
+
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
1640
|
+
|
|
1641
|
+
- 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`).
|
|
1642
|
+
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
1643
|
+
|
|
1644
|
+
@default true
|
|
1645
|
+
|
|
1646
|
+
@example
|
|
1647
|
+
```
|
|
1648
|
+
import type {AllExtend} from 'type-fest';
|
|
1649
|
+
|
|
1650
|
+
type A = AllExtend<[1, 2, never], number, {strictNever: true}>;
|
|
1651
|
+
//=> false
|
|
1652
|
+
|
|
1653
|
+
type B = AllExtend<[1, 2, never], number, {strictNever: false}>;
|
|
1654
|
+
//=> true
|
|
1655
|
+
|
|
1656
|
+
type C = AllExtend<[never, never], never, {strictNever: true}>;
|
|
1657
|
+
//=> true
|
|
1658
|
+
|
|
1659
|
+
type D = AllExtend<[never, never], never, {strictNever: false}>;
|
|
1660
|
+
//=> true
|
|
1661
|
+
|
|
1662
|
+
type E = AllExtend<['a', 'b', never], any, {strictNever: true}>;
|
|
1663
|
+
//=> true
|
|
1664
|
+
|
|
1665
|
+
type F = AllExtend<['a', 'b', never], any, {strictNever: false}>;
|
|
1666
|
+
//=> true
|
|
1667
|
+
|
|
1668
|
+
type G = AllExtend<[never, 1], never, {strictNever: true}>;
|
|
1669
|
+
//=> false
|
|
1670
|
+
|
|
1671
|
+
type H = AllExtend<[never, 1], never, {strictNever: false}>;
|
|
1672
|
+
//=> false
|
|
1673
|
+
```
|
|
1674
|
+
*/
|
|
1675
|
+
strictNever?: boolean;
|
|
1676
|
+
};
|
|
1677
|
+
type DefaultAllExtendOptions = {
|
|
1678
|
+
strictNever: true;
|
|
1679
|
+
};
|
|
1680
|
+
/**
|
|
1681
|
+
Returns a boolean for whether every element in an array type extends another type.
|
|
1682
|
+
|
|
1683
|
+
@example
|
|
1684
|
+
```
|
|
1685
|
+
import type {AllExtend} from 'type-fest';
|
|
1686
|
+
|
|
1687
|
+
type A = AllExtend<[1, 2, 3], number>;
|
|
1688
|
+
//=> true
|
|
1689
|
+
|
|
1690
|
+
type B = AllExtend<[1, 2, '3'], number>;
|
|
1691
|
+
//=> false
|
|
1692
|
+
|
|
1693
|
+
type C = AllExtend<[number, number | string], number>;
|
|
1694
|
+
//=> boolean
|
|
1695
|
+
|
|
1696
|
+
type D = AllExtend<[true, boolean, true], true>;
|
|
1697
|
+
//=> boolean
|
|
1698
|
+
```
|
|
1699
|
+
|
|
1700
|
+
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.
|
|
1701
|
+
|
|
1702
|
+
```
|
|
1703
|
+
// @exactOptionalPropertyTypes: true
|
|
1704
|
+
import type {AllExtend} from 'type-fest';
|
|
1705
|
+
|
|
1706
|
+
type A = AllExtend<[1?, 2?, 3?], number>;
|
|
1707
|
+
//=> true
|
|
1708
|
+
```
|
|
1709
|
+
|
|
1710
|
+
```
|
|
1711
|
+
// @exactOptionalPropertyTypes: false
|
|
1712
|
+
import type {AllExtend} from 'type-fest';
|
|
1713
|
+
|
|
1714
|
+
type A = AllExtend<[1?, 2?, 3?], number>;
|
|
1715
|
+
//=> boolean
|
|
1716
|
+
|
|
1717
|
+
type B = AllExtend<[1?, 2?, 3?], number | undefined>;
|
|
1718
|
+
//=> true
|
|
1719
|
+
```
|
|
1720
|
+
|
|
1721
|
+
@see {@link AllExtendOptions}
|
|
1722
|
+
|
|
1723
|
+
@category Utilities
|
|
1724
|
+
@category Array
|
|
1725
|
+
*/
|
|
1726
|
+
type AllExtend<TArray extends UnknownArray, Type, Options extends AllExtendOptions = {}> = _AllExtend<CollapseRestElement<TArray>, Type, ApplyDefaultOptions<AllExtendOptions, DefaultAllExtendOptions, Options>>;
|
|
1727
|
+
type _AllExtend<TArray extends UnknownArray, Type, Options extends Required<AllExtendOptions>> = IfNotAnyOrNever<TArray, {
|
|
1728
|
+
ifNot: TArray extends readonly [infer First, ...infer Rest] ? IsNever<First> extends true ? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true ?
|
|
1729
|
+
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, recurse further.
|
|
1730
|
+
_AllExtend<Rest, Type, Options> : false : First extends Type ? _AllExtend<Rest, Type, Options> : false : true;
|
|
1731
|
+
ifAny: false;
|
|
1732
|
+
ifNever: false;
|
|
1733
|
+
}>;
|
|
1734
|
+
/**
|
|
1735
|
+
Returns a boolean for whether all of the given elements are `true`.
|
|
1736
|
+
|
|
1737
|
+
Use-cases:
|
|
1738
|
+
- Check if all conditions in a list of booleans are met.
|
|
1739
|
+
|
|
1740
|
+
@example
|
|
1741
|
+
```
|
|
1742
|
+
import type {AndAll} from 'type-fest';
|
|
1743
|
+
|
|
1744
|
+
type TTT = AndAll<[true, true, true]>;
|
|
1745
|
+
//=> true
|
|
1746
|
+
|
|
1747
|
+
type TTF = AndAll<[true, true, false]>;
|
|
1748
|
+
//=> false
|
|
1749
|
+
|
|
1750
|
+
type TFT = AndAll<[true, false, true]>;
|
|
1751
|
+
//=> false
|
|
1752
|
+
```
|
|
1753
|
+
|
|
1754
|
+
Note: When `boolean` is passed as an element, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1755
|
+
For example, `AndAll<[true, boolean]>` expands to `AndAll<[true, true]> | AndAll<[true, false]>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
1756
|
+
|
|
1757
|
+
@example
|
|
1758
|
+
```
|
|
1759
|
+
import type {AndAll} from 'type-fest';
|
|
1760
|
+
|
|
1761
|
+
type A = AndAll<[true, boolean]>;
|
|
1762
|
+
//=> boolean
|
|
1763
|
+
|
|
1764
|
+
type B = AndAll<[false, boolean]>;
|
|
1765
|
+
//=> false
|
|
1766
|
+
```
|
|
1767
|
+
|
|
1768
|
+
Note: If any of the elements is `never`, the result becomes `false`.
|
|
1769
|
+
|
|
1770
|
+
@example
|
|
1771
|
+
```
|
|
1772
|
+
import type {AndAll} from 'type-fest';
|
|
1773
|
+
|
|
1774
|
+
type A = AndAll<[true, true, never]>;
|
|
1775
|
+
//=> false
|
|
1776
|
+
|
|
1777
|
+
type B = AndAll<[false, never, never]>;
|
|
1778
|
+
//=> false
|
|
1779
|
+
|
|
1780
|
+
type C = AndAll<[never, never, never]>;
|
|
1781
|
+
//=> false
|
|
1782
|
+
|
|
1783
|
+
type D = AndAll<[boolean, true, never]>;
|
|
1784
|
+
//=> false
|
|
1785
|
+
```
|
|
1786
|
+
|
|
1787
|
+
Note: If `any` is passed as an element, it is treated as `boolean` and the result is computed accordingly.
|
|
1788
|
+
|
|
1789
|
+
@example
|
|
1790
|
+
```
|
|
1791
|
+
import type {AndAll} from 'type-fest';
|
|
1792
|
+
|
|
1793
|
+
type A = AndAll<[false, any]>;
|
|
1794
|
+
//=> false
|
|
1795
|
+
|
|
1796
|
+
type B = AndAll<[true, any]>;
|
|
1797
|
+
//=> boolean
|
|
1798
|
+
```
|
|
1799
|
+
|
|
1800
|
+
Note: `AndAll<[]>` evaluates to `true` due to the concept of [vacuous truth](https://en.wikipedia.org/wiki/Logical_conjunction#:~:text=In%20keeping%20with%20the%20concept%20of%20vacuous%20truth%2C%20when%20conjunction%20is%20defined%20as%20an%20operator%20or%20function%20of%20arbitrary%20arity%2C%20the%20empty%20conjunction%20(AND%2Ding%20over%20an%20empty%20set%20of%20operands)%20is%20often%20defined%20as%20having%20the%20result%20true.), i.e., there are no `false` elements in an empty tuple.
|
|
1801
|
+
|
|
1802
|
+
@see {@link And}
|
|
1803
|
+
@see {@link OrAll}
|
|
1804
|
+
*/
|
|
1805
|
+
type AndAll<T extends readonly boolean[]> = AllExtend<T, true>;
|
|
1806
|
+
/**
|
|
1807
|
+
Returns a boolean for whether two given types are both `true`.
|
|
1808
|
+
|
|
1809
|
+
Use-case: Constructing complex conditional types where multiple conditions must be satisfied.
|
|
1810
|
+
|
|
1811
|
+
@example
|
|
1812
|
+
```
|
|
1813
|
+
import type {And} from 'type-fest';
|
|
1814
|
+
|
|
1815
|
+
type TT = And<true, true>;
|
|
1816
|
+
//=> true
|
|
1817
|
+
|
|
1818
|
+
type TF = And<true, false>;
|
|
1819
|
+
//=> false
|
|
1820
|
+
|
|
1821
|
+
type FT = And<false, true>;
|
|
1822
|
+
//=> false
|
|
1823
|
+
|
|
1824
|
+
type FF = And<false, false>;
|
|
1825
|
+
//=> false
|
|
1826
|
+
```
|
|
1827
|
+
|
|
1828
|
+
Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1829
|
+
For example, `And<true, boolean>` expands to `And<true, true> | And<true, false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
1830
|
+
|
|
1831
|
+
@example
|
|
1832
|
+
```
|
|
1833
|
+
import type {And} from 'type-fest';
|
|
1834
|
+
|
|
1835
|
+
type A = And<true, boolean>;
|
|
1836
|
+
//=> boolean
|
|
1837
|
+
|
|
1838
|
+
type B = And<boolean, true>;
|
|
1839
|
+
//=> boolean
|
|
1840
|
+
|
|
1841
|
+
type C = And<false, boolean>;
|
|
1842
|
+
//=> false
|
|
1843
|
+
|
|
1844
|
+
type D = And<boolean, false>;
|
|
1845
|
+
//=> false
|
|
1846
|
+
|
|
1847
|
+
type E = And<boolean, boolean>;
|
|
1848
|
+
//=> boolean
|
|
1849
|
+
```
|
|
1850
|
+
|
|
1851
|
+
Note: If either of the types is `never`, the result becomes `false`.
|
|
1852
|
+
|
|
1853
|
+
@example
|
|
1854
|
+
```
|
|
1855
|
+
import type {And} from 'type-fest';
|
|
1856
|
+
|
|
1857
|
+
type A = And<true, never>;
|
|
1858
|
+
//=> false
|
|
1859
|
+
|
|
1860
|
+
type B = And<never, true>;
|
|
1861
|
+
//=> false
|
|
1862
|
+
|
|
1863
|
+
type C = And<false, never>;
|
|
1864
|
+
//=> false
|
|
1865
|
+
|
|
1866
|
+
type D = And<never, false>;
|
|
1867
|
+
//=> false
|
|
1868
|
+
|
|
1869
|
+
type E = And<boolean, never>;
|
|
1870
|
+
//=> false
|
|
1871
|
+
|
|
1872
|
+
type F = And<never, boolean>;
|
|
1873
|
+
//=> false
|
|
1874
|
+
|
|
1875
|
+
type G = And<never, never>;
|
|
1876
|
+
//=> false
|
|
1877
|
+
```
|
|
1878
|
+
|
|
1879
|
+
@see {@link AndAll}
|
|
1880
|
+
@see {@link Or}
|
|
1881
|
+
@see {@link Xor}
|
|
1882
|
+
*/
|
|
1883
|
+
type And<A extends boolean, B extends boolean> = AndAll<[A, B]>;
|
|
1884
|
+
/**
|
|
1885
|
+
Returns the absolute value of the specified number or bigint.
|
|
1886
|
+
|
|
1887
|
+
@example
|
|
1888
|
+
```
|
|
1889
|
+
import type {Absolute} from 'type-fest';
|
|
1890
|
+
|
|
1891
|
+
type A = Absolute<-1>;
|
|
1892
|
+
//=> 1
|
|
1893
|
+
|
|
1894
|
+
type B = Absolute<1>;
|
|
1895
|
+
//=> 1
|
|
1896
|
+
|
|
1897
|
+
type C = Absolute<0>;
|
|
1898
|
+
//=> 0
|
|
1899
|
+
|
|
1900
|
+
type D = Absolute<-1.025>;
|
|
1901
|
+
//=> 1.025
|
|
1902
|
+
|
|
1903
|
+
type E = Absolute<-9999n>;
|
|
1904
|
+
//=> 9999n
|
|
1905
|
+
```
|
|
1906
|
+
|
|
1907
|
+
Returns back the same type if the input is not a literal type.
|
|
1908
|
+
|
|
1909
|
+
@example
|
|
1910
|
+
```
|
|
1911
|
+
import type {Absolute} from 'type-fest';
|
|
1912
|
+
|
|
1913
|
+
type A = Absolute<number>;
|
|
1914
|
+
//=> number
|
|
1915
|
+
|
|
1916
|
+
type B = Absolute<bigint>;
|
|
1917
|
+
//=> bigint
|
|
1918
|
+
|
|
1919
|
+
type C = Absolute<number | bigint>;
|
|
1920
|
+
//=> number | bigint
|
|
1921
|
+
```
|
|
1922
|
+
|
|
1923
|
+
@category Numeric
|
|
1924
|
+
*/
|
|
1925
|
+
type Absolute<N extends number | bigint> = N extends bigint // Also, distributes `N`
|
|
1926
|
+
? `${N}` extends `-${infer Magnitude extends bigint}` ? Magnitude : N : `${N}` extends `-${infer Magnitude}` // This doesn't use the `extends number` constraint approach because that fails with the `-Infinity` case
|
|
1927
|
+
? StringToNumber<Magnitude> : N;
|
|
1928
|
+
/**
|
|
1929
|
+
Returns a boolean for whether a given number is greater than another number.
|
|
1930
|
+
|
|
1931
|
+
@example
|
|
1932
|
+
```
|
|
1933
|
+
import type {GreaterThan} from 'type-fest';
|
|
1934
|
+
|
|
1935
|
+
type A = GreaterThan<1, -5>;
|
|
1936
|
+
//=> true
|
|
1937
|
+
|
|
1938
|
+
type B = GreaterThan<1, 1>;
|
|
1939
|
+
//=> false
|
|
1940
|
+
|
|
1941
|
+
type C = GreaterThan<1, 5>;
|
|
1942
|
+
//=> false
|
|
1943
|
+
```
|
|
1944
|
+
|
|
1945
|
+
Note: If either argument is the non-literal `number` type, the result is `boolean`.
|
|
1946
|
+
|
|
1947
|
+
@example
|
|
1948
|
+
```
|
|
1949
|
+
import type {GreaterThan} from 'type-fest';
|
|
1950
|
+
|
|
1951
|
+
type A = GreaterThan<number, 1>;
|
|
1952
|
+
//=> boolean
|
|
1953
|
+
|
|
1954
|
+
type B = GreaterThan<1, number>;
|
|
1955
|
+
//=> boolean
|
|
1956
|
+
|
|
1957
|
+
type C = GreaterThan<number, number>;
|
|
1958
|
+
//=> boolean
|
|
1959
|
+
```
|
|
1960
|
+
|
|
1961
|
+
@example
|
|
1962
|
+
```
|
|
1963
|
+
import type {GreaterThan} from 'type-fest';
|
|
1964
|
+
|
|
1965
|
+
// Use `GreaterThan` to constrain a function parameter to positive numbers.
|
|
1966
|
+
declare function setPositive<N extends number>(value: GreaterThan<N, 0> extends true ? N : never): void;
|
|
1967
|
+
|
|
1968
|
+
setPositive(1); // ✅ Allowed
|
|
1969
|
+
setPositive(2); // ✅ Allowed
|
|
1970
|
+
|
|
1971
|
+
// @ts-expect-error
|
|
1972
|
+
setPositive(0);
|
|
1973
|
+
|
|
1974
|
+
// @ts-expect-error
|
|
1975
|
+
setPositive(-1);
|
|
1976
|
+
```
|
|
1977
|
+
*/
|
|
1978
|
+
type GreaterThan<A extends number, B extends number> = A extends number // For distributing `A`
|
|
1979
|
+
? B extends number // For distributing `B`
|
|
1980
|
+
? number extends A | B ? boolean : [IsEqual<A, PositiveInfinity>, IsEqual<A, NegativeInfinity>, IsEqual<B, PositiveInfinity>, IsEqual<B, NegativeInfinity>] extends (infer R extends [boolean, boolean, boolean, boolean]) ? Or<And<IsEqual<R[0], true>, IsEqual<R[2], false>>, And<IsEqual<R[3], true>, IsEqual<R[1], false>>> extends true ? true : Or<And<IsEqual<R[1], true>, IsEqual<R[3], false>>, And<IsEqual<R[2], true>, IsEqual<R[0], false>>> extends true ? false : true extends R[number] ? false : [IsNegative<A>, IsNegative<B>] extends (infer R extends [boolean, boolean]) ? [true, false] extends R ? false : [false, true] extends R ? true : [false, false] extends R ? PositiveNumericStringGt<`${A}`, `${B}`> : PositiveNumericStringGt<`${Absolute<B>}`, `${Absolute<A>}`> : never : never : never // Should never happen
|
|
1981
|
+
: never; // Should never happen
|
|
1982
|
+
/**
|
|
1983
|
+
Returns a boolean for whether a given number is greater than or equal to another number.
|
|
1984
|
+
|
|
1985
|
+
@example
|
|
1986
|
+
```
|
|
1987
|
+
import type {GreaterThanOrEqual} from 'type-fest';
|
|
1988
|
+
|
|
1989
|
+
type A = GreaterThanOrEqual<1, -5>;
|
|
1990
|
+
//=> true
|
|
1991
|
+
|
|
1992
|
+
type B = GreaterThanOrEqual<1, 1>;
|
|
1993
|
+
//=> true
|
|
1994
|
+
|
|
1995
|
+
type C = GreaterThanOrEqual<1, 5>;
|
|
1996
|
+
//=> false
|
|
1997
|
+
```
|
|
1998
|
+
|
|
1999
|
+
Note: If either argument is the non-literal `number` type, the result is `boolean`.
|
|
2000
|
+
|
|
2001
|
+
@example
|
|
2002
|
+
```
|
|
2003
|
+
import type {GreaterThanOrEqual} from 'type-fest';
|
|
2004
|
+
|
|
2005
|
+
type A = GreaterThanOrEqual<number, 1>;
|
|
2006
|
+
//=> boolean
|
|
2007
|
+
|
|
2008
|
+
type B = GreaterThanOrEqual<1, number>;
|
|
2009
|
+
//=> boolean
|
|
2010
|
+
|
|
2011
|
+
type C = GreaterThanOrEqual<number, number>;
|
|
2012
|
+
//=> boolean
|
|
2013
|
+
```
|
|
2014
|
+
|
|
2015
|
+
@example
|
|
2016
|
+
```
|
|
2017
|
+
import type {GreaterThanOrEqual} from 'type-fest';
|
|
2018
|
+
|
|
2019
|
+
// Use `GreaterThanOrEqual` to constrain a function parameter to non-negative numbers.
|
|
2020
|
+
declare function setNonNegative<N extends number>(value: GreaterThanOrEqual<N, 0> extends true ? N : never): void;
|
|
2021
|
+
|
|
2022
|
+
setNonNegative(0); // ✅ Allowed
|
|
2023
|
+
setNonNegative(1); // ✅ Allowed
|
|
2024
|
+
|
|
2025
|
+
// @ts-expect-error
|
|
2026
|
+
setNonNegative(-1);
|
|
2027
|
+
|
|
2028
|
+
// @ts-expect-error
|
|
2029
|
+
setNonNegative(-2);
|
|
2030
|
+
```
|
|
2031
|
+
*/
|
|
2032
|
+
type GreaterThanOrEqual<A extends number, B extends number> = number extends A | B ? boolean : A extends number // For distributing `A`
|
|
2033
|
+
? B extends number // For distributing `B`
|
|
2034
|
+
? A extends B ? true : GreaterThan<A, B> : never // Should never happen
|
|
2035
|
+
: never; // Should never happen
|
|
2036
|
+
/**
|
|
2037
|
+
Returns a boolean for whether a given number is less than another number.
|
|
2038
|
+
|
|
2039
|
+
@example
|
|
2040
|
+
```
|
|
2041
|
+
import type {LessThan} from 'type-fest';
|
|
2042
|
+
|
|
2043
|
+
type A = LessThan<1, -5>;
|
|
2044
|
+
//=> false
|
|
2045
|
+
|
|
2046
|
+
type B = LessThan<1, 1>;
|
|
2047
|
+
//=> false
|
|
2048
|
+
|
|
2049
|
+
type C = LessThan<1, 5>;
|
|
2050
|
+
//=> true
|
|
2051
|
+
```
|
|
2052
|
+
|
|
2053
|
+
Note: If either argument is the non-literal `number` type, the result is `boolean`.
|
|
2054
|
+
|
|
2055
|
+
@example
|
|
2056
|
+
```
|
|
2057
|
+
import type {LessThan} from 'type-fest';
|
|
2058
|
+
|
|
2059
|
+
type A = LessThan<number, 1>;
|
|
2060
|
+
//=> boolean
|
|
2061
|
+
|
|
2062
|
+
type B = LessThan<1, number>;
|
|
2063
|
+
//=> boolean
|
|
2064
|
+
|
|
2065
|
+
type C = LessThan<number, number>;
|
|
2066
|
+
//=> boolean
|
|
2067
|
+
```
|
|
2068
|
+
|
|
2069
|
+
@example
|
|
2070
|
+
```
|
|
2071
|
+
import type {LessThan} from 'type-fest';
|
|
2072
|
+
|
|
2073
|
+
// Use `LessThan` to constrain a function parameter to negative numbers.
|
|
2074
|
+
declare function setNegative<N extends number>(value: LessThan<N, 0> extends true ? N : never): void;
|
|
2075
|
+
|
|
2076
|
+
setNegative(-1); // ✅ Allowed
|
|
2077
|
+
setNegative(-2); // ✅ Allowed
|
|
2078
|
+
|
|
2079
|
+
// @ts-expect-error
|
|
2080
|
+
setNegative(0);
|
|
2081
|
+
|
|
2082
|
+
// @ts-expect-error
|
|
2083
|
+
setNegative(1);
|
|
2084
|
+
```
|
|
2085
|
+
*/
|
|
2086
|
+
type LessThan<A extends number, B extends number> = GreaterThanOrEqual<A, B> extends (infer Result) ? Result extends true ? false : true : never; // Should never happen
|
|
2087
|
+
/**
|
|
2088
|
+
Returns the maximum value from a tuple of integers.
|
|
2089
|
+
|
|
2090
|
+
Note:
|
|
2091
|
+
- Float numbers are not supported.
|
|
2092
|
+
|
|
2093
|
+
@example
|
|
2094
|
+
```
|
|
2095
|
+
type A = TupleMax<[1, 2, 5, 3]>;
|
|
2096
|
+
//=> 5
|
|
2097
|
+
|
|
2098
|
+
type B = TupleMax<[1, 2, 5, 3, 99, -1]>;
|
|
2099
|
+
//=> 99
|
|
2100
|
+
```
|
|
2101
|
+
*/
|
|
2102
|
+
type TupleMax<A extends number[], Result extends number = NegativeInfinity> = number extends A[number] ? never : A extends [infer F extends number, ...infer R extends number[]] ? GreaterThan<F, Result> extends true ? TupleMax<R, F> : TupleMax<R, Result> : Result;
|
|
2103
|
+
/**
|
|
2104
|
+
Returns the difference between two numbers.
|
|
2105
|
+
|
|
2106
|
+
Note:
|
|
2107
|
+
- A or B can only support `-999` ~ `999`.
|
|
2108
|
+
|
|
2109
|
+
@example
|
|
2110
|
+
```
|
|
2111
|
+
import type {Subtract, PositiveInfinity} from 'type-fest';
|
|
2112
|
+
|
|
2113
|
+
type A = Subtract<333, 222>;
|
|
2114
|
+
//=> 111
|
|
2115
|
+
|
|
2116
|
+
type B = Subtract<111, -222>;
|
|
2117
|
+
//=> 333
|
|
2118
|
+
|
|
2119
|
+
type C = Subtract<-111, 222>;
|
|
2120
|
+
//=> -333
|
|
2121
|
+
|
|
2122
|
+
type D = Subtract<18, 96>;
|
|
2123
|
+
//=> -78
|
|
2124
|
+
|
|
2125
|
+
type E = Subtract<PositiveInfinity, 9999>;
|
|
2126
|
+
//=> Infinity
|
|
2127
|
+
|
|
2128
|
+
type F = Subtract<PositiveInfinity, PositiveInfinity>;
|
|
2129
|
+
//=> number
|
|
2130
|
+
```
|
|
2131
|
+
|
|
2132
|
+
@category Numeric
|
|
2133
|
+
*/
|
|
2134
|
+
// TODO: Support big integer.
|
|
2135
|
+
type Subtract<A extends number, B extends number> =
|
|
2136
|
+
// Handle cases when A or B is the actual "number" type
|
|
2137
|
+
number extends A | B ? number :
|
|
2138
|
+
// Handle cases when A and B are both +/- infinity
|
|
2139
|
+
A extends B & (PositiveInfinity | NegativeInfinity) ? number :
|
|
2140
|
+
// Handle cases when A is - infinity or B is + infinity
|
|
2141
|
+
A extends NegativeInfinity ? NegativeInfinity : B extends PositiveInfinity ? NegativeInfinity :
|
|
2142
|
+
// Handle cases when A is + infinity or B is - infinity
|
|
2143
|
+
A extends PositiveInfinity ? PositiveInfinity : B extends NegativeInfinity ? PositiveInfinity :
|
|
2144
|
+
// Handle case when numbers are equal to each other
|
|
2145
|
+
A extends B ? 0 :
|
|
2146
|
+
// Handle cases when A or B is 0
|
|
2147
|
+
A extends 0 ? ReverseSign<B> : B extends 0 ? A :
|
|
2148
|
+
// Handle remaining regular cases
|
|
2149
|
+
SubtractPostChecks<A, B>;
|
|
2150
|
+
/**
|
|
2151
|
+
Subtracts two numbers A and B, such that they are not equal and neither of them are 0, +/- infinity or the `number` type
|
|
2152
|
+
*/
|
|
2153
|
+
type SubtractPostChecks<A extends number, B extends number, AreNegative = [IsNegative<A>, IsNegative<B>]> = AreNegative extends [false, false] ? SubtractPositives<A, B> : AreNegative extends [true, true] ?
|
|
2154
|
+
// When both numbers are negative we subtract the absolute values and then reverse the sign
|
|
2155
|
+
ReverseSign<SubtractPositives<Absolute<A>, Absolute<B>>> :
|
|
2156
|
+
// When the signs are different we can add the absolute values and then reverse the sign if A < B
|
|
2157
|
+
[...TupleOf<Absolute<A>>, ...TupleOf<Absolute<B>>] extends (infer R extends unknown[]) ? LessThan<A, B> extends true ? ReverseSign<R['length']> : R['length'] : never;
|
|
2158
|
+
/**
|
|
2159
|
+
Subtracts two positive numbers.
|
|
2160
|
+
*/
|
|
2161
|
+
type SubtractPositives<A extends number, B extends number> = LessThan<A, B> extends true ?
|
|
2162
|
+
// When A < B we can reverse the result of B - A
|
|
2163
|
+
ReverseSign<SubtractIfAGreaterThanB<B, A>> : SubtractIfAGreaterThanB<A, B>;
|
|
2164
|
+
/**
|
|
2165
|
+
Subtracts two positive numbers A and B such that A > B.
|
|
2166
|
+
*/
|
|
2167
|
+
type SubtractIfAGreaterThanB<A extends number, B extends number> =
|
|
2168
|
+
// This is where we always want to end up and do the actual subtraction
|
|
2169
|
+
TupleOf<A> extends [...TupleOf<B>, ...infer R] ? R['length'] : never;
|
|
2170
|
+
/**
|
|
2171
|
+
Returns the sum of two numbers.
|
|
2172
|
+
|
|
2173
|
+
Note:
|
|
2174
|
+
- A or B can only support `-999` ~ `999`.
|
|
2175
|
+
|
|
2176
|
+
@example
|
|
2177
|
+
```
|
|
2178
|
+
import type {Sum, PositiveInfinity, NegativeInfinity} from 'type-fest';
|
|
2179
|
+
|
|
2180
|
+
type A = Sum<111, 222>;
|
|
2181
|
+
//=> 333
|
|
2182
|
+
|
|
2183
|
+
type B = Sum<-111, 222>;
|
|
2184
|
+
//=> 111
|
|
2185
|
+
|
|
2186
|
+
type C = Sum<111, -222>;
|
|
2187
|
+
//=> -111
|
|
2188
|
+
|
|
2189
|
+
type D = Sum<PositiveInfinity, -9999>;
|
|
2190
|
+
//=> Infinity
|
|
2191
|
+
|
|
2192
|
+
type E = Sum<PositiveInfinity, NegativeInfinity>;
|
|
2193
|
+
//=> number
|
|
2194
|
+
```
|
|
2195
|
+
|
|
2196
|
+
@category Numeric
|
|
2197
|
+
*/
|
|
2198
|
+
// TODO: Support big integer.
|
|
2199
|
+
type Sum<A extends number, B extends number> =
|
|
2200
|
+
// Handle cases when A or B is the actual "number" type
|
|
2201
|
+
number extends A | B ? number :
|
|
2202
|
+
// Handle cases when A and B are both +/- infinity
|
|
2203
|
+
A extends B & (PositiveInfinity | NegativeInfinity) ? A // A or B could be used here as they are equal
|
|
2204
|
+
:
|
|
2205
|
+
// Handle cases when A and B are opposite infinities
|
|
2206
|
+
A | B extends PositiveInfinity | NegativeInfinity ? number :
|
|
2207
|
+
// Handle cases when A is +/- infinity
|
|
2208
|
+
A extends PositiveInfinity | NegativeInfinity ? A :
|
|
2209
|
+
// Handle cases when B is +/- infinity
|
|
2210
|
+
B extends PositiveInfinity | NegativeInfinity ? B :
|
|
2211
|
+
// Handle cases when A or B is 0 or it's the same number with different signs
|
|
2212
|
+
A extends 0 ? B : B extends 0 ? A : A extends ReverseSign<B> ? 0 :
|
|
2213
|
+
// Handle remaining regular cases
|
|
2214
|
+
SumPostChecks<A, B>;
|
|
2215
|
+
/**
|
|
2216
|
+
Adds two numbers A and B, such that they are not equal with different signs and neither of them are 0, +/- infinity or the `number` type
|
|
2217
|
+
*/
|
|
2218
|
+
type SumPostChecks<A extends number, B extends number, AreNegative = [IsNegative<A>, IsNegative<B>]> = AreNegative extends [false, false] ?
|
|
2219
|
+
// When both numbers are positive we can add them together
|
|
2220
|
+
SumPositives<A, B> : AreNegative extends [true, true] ?
|
|
2221
|
+
// When both numbers are negative we add the absolute values and then reverse the sign
|
|
2222
|
+
ReverseSign<SumPositives<Absolute<A>, Absolute<B>>> :
|
|
2223
|
+
// When the signs are different we can subtract the absolute values, remove the sign
|
|
2224
|
+
// and then reverse the sign if the larger absolute value is negative
|
|
2225
|
+
Absolute<Subtract<Absolute<A>, Absolute<B>>> extends (infer Result extends number) ? TupleMax<[Absolute<A>, Absolute<B>]> extends (infer Max_ extends number) ? Max_ extends A | B ?
|
|
2226
|
+
// The larger absolute value is positive, so the result is positive
|
|
2227
|
+
Result :
|
|
2228
|
+
// The larger absolute value is negative, so the result is negative
|
|
2229
|
+
ReverseSign<Result> : never : never;
|
|
2230
|
+
/**
|
|
2231
|
+
Adds two positive numbers.
|
|
2232
|
+
*/
|
|
2233
|
+
type SumPositives<A extends number, B extends number> = [...TupleOf<A>, ...TupleOf<B>]['length'] extends (infer Result extends number) ? Result : never;
|
|
2234
|
+
/**
|
|
2235
|
+
Paths options.
|
|
2236
|
+
|
|
2237
|
+
@see {@link Paths}
|
|
2238
|
+
*/
|
|
2239
|
+
type PathsOptions = {
|
|
2240
|
+
/**
|
|
2241
|
+
The maximum depth to recurse when searching for paths. Range: 0 ~ 10.
|
|
2242
|
+
|
|
2243
|
+
@default 5
|
|
2244
|
+
*/
|
|
2245
|
+
maxRecursionDepth?: number;
|
|
2246
|
+
/**
|
|
2247
|
+
Use bracket notation for array indices and numeric object keys.
|
|
2248
|
+
|
|
2249
|
+
@default false
|
|
2250
|
+
|
|
2251
|
+
@example
|
|
2252
|
+
```
|
|
2253
|
+
import type {Paths} from 'type-fest';
|
|
2254
|
+
|
|
2255
|
+
type ArrayExample = {
|
|
2256
|
+
array: ['foo'];
|
|
2257
|
+
};
|
|
2258
|
+
|
|
2259
|
+
type A = Paths<ArrayExample, {bracketNotation: false}>;
|
|
2260
|
+
//=> 'array' | 'array.0'
|
|
2261
|
+
|
|
2262
|
+
type B = Paths<ArrayExample, {bracketNotation: true}>;
|
|
2263
|
+
//=> 'array' | 'array[0]'
|
|
2264
|
+
```
|
|
2265
|
+
|
|
2266
|
+
@example
|
|
2267
|
+
```
|
|
2268
|
+
import type {Paths} from 'type-fest';
|
|
2269
|
+
|
|
2270
|
+
type NumberKeyExample = {
|
|
2271
|
+
1: ['foo'];
|
|
2272
|
+
};
|
|
2273
|
+
|
|
2274
|
+
type A = Paths<NumberKeyExample, {bracketNotation: false}>;
|
|
2275
|
+
//=> 1 | '1' | '1.0'
|
|
2276
|
+
|
|
2277
|
+
type B = Paths<NumberKeyExample, {bracketNotation: true}>;
|
|
2278
|
+
//=> '[1]' | '[1][0]'
|
|
2279
|
+
```
|
|
2280
|
+
*/
|
|
2281
|
+
bracketNotation?: boolean;
|
|
2282
|
+
/**
|
|
2283
|
+
Only include leaf paths in the output.
|
|
2284
|
+
|
|
2285
|
+
@default false
|
|
2286
|
+
|
|
2287
|
+
@example
|
|
2288
|
+
```
|
|
2289
|
+
import type {Paths} from 'type-fest';
|
|
2290
|
+
|
|
2291
|
+
type Post = {
|
|
2292
|
+
id: number;
|
|
2293
|
+
author: {
|
|
2294
|
+
id: number;
|
|
2295
|
+
name: {
|
|
2296
|
+
first: string;
|
|
2297
|
+
last: string;
|
|
2298
|
+
};
|
|
2299
|
+
};
|
|
2300
|
+
};
|
|
2301
|
+
|
|
2302
|
+
type AllPaths = Paths<Post, {leavesOnly: false}>;
|
|
2303
|
+
//=> 'id' | 'author' | 'author.id' | 'author.name' | 'author.name.first' | 'author.name.last'
|
|
2304
|
+
|
|
2305
|
+
type LeafPaths = Paths<Post, {leavesOnly: true}>;
|
|
2306
|
+
//=> 'id' | 'author.id' | 'author.name.first' | 'author.name.last'
|
|
2307
|
+
```
|
|
2308
|
+
|
|
2309
|
+
@example
|
|
2310
|
+
```
|
|
2311
|
+
import type {Paths} from 'type-fest';
|
|
2312
|
+
|
|
2313
|
+
type ArrayExample = {
|
|
2314
|
+
array: Array<{foo: string}>;
|
|
2315
|
+
tuple: [string, {bar: string}];
|
|
2316
|
+
};
|
|
2317
|
+
|
|
2318
|
+
type AllPaths = Paths<ArrayExample, {leavesOnly: false}>;
|
|
2319
|
+
//=> 'array' | 'tuple' | `array.${number}` | `array.${number}.foo` | 'tuple.0' | 'tuple.1' | 'tuple.1.bar'
|
|
2320
|
+
|
|
2321
|
+
type LeafPaths = Paths<ArrayExample, {leavesOnly: true}>;
|
|
2322
|
+
//=> `array.${number}.foo` | 'tuple.0' | 'tuple.1.bar'
|
|
2323
|
+
```
|
|
2324
|
+
*/
|
|
2325
|
+
leavesOnly?: boolean;
|
|
2326
|
+
/**
|
|
2327
|
+
Only include paths at the specified depth. By default all paths up to {@link PathsOptions.maxRecursionDepth | `maxRecursionDepth`} are included.
|
|
2328
|
+
|
|
2329
|
+
Note: Depth starts at `0` for root properties.
|
|
2330
|
+
|
|
2331
|
+
@default number
|
|
2332
|
+
|
|
2333
|
+
@example
|
|
2334
|
+
```
|
|
2335
|
+
import type {Paths} from 'type-fest';
|
|
2336
|
+
|
|
2337
|
+
type Post = {
|
|
2338
|
+
id: number;
|
|
2339
|
+
author: {
|
|
2340
|
+
id: number;
|
|
2341
|
+
name: {
|
|
2342
|
+
first: string;
|
|
2343
|
+
last: string;
|
|
2344
|
+
};
|
|
2345
|
+
};
|
|
2346
|
+
};
|
|
2347
|
+
|
|
2348
|
+
type DepthZero = Paths<Post, {depth: 0}>;
|
|
2349
|
+
//=> 'id' | 'author'
|
|
2350
|
+
|
|
2351
|
+
type DepthOne = Paths<Post, {depth: 1}>;
|
|
2352
|
+
//=> 'author.id' | 'author.name'
|
|
2353
|
+
|
|
2354
|
+
type DepthTwo = Paths<Post, {depth: 2}>;
|
|
2355
|
+
//=> 'author.name.first' | 'author.name.last'
|
|
2356
|
+
|
|
2357
|
+
type LeavesAtDepthOne = Paths<Post, {leavesOnly: true; depth: 1}>;
|
|
2358
|
+
//=> 'author.id'
|
|
2359
|
+
```
|
|
2360
|
+
*/
|
|
2361
|
+
depth?: number;
|
|
2362
|
+
};
|
|
2363
|
+
type DefaultPathsOptions = {
|
|
2364
|
+
maxRecursionDepth: 5;
|
|
2365
|
+
bracketNotation: false;
|
|
2366
|
+
leavesOnly: false;
|
|
2367
|
+
depth: number;
|
|
2368
|
+
};
|
|
2369
|
+
/**
|
|
2370
|
+
Generate a union of all possible paths to properties in the given object.
|
|
2371
|
+
|
|
2372
|
+
It also works with arrays.
|
|
2373
|
+
|
|
2374
|
+
Use-case: You want a type-safe way to access deeply nested properties in an object.
|
|
2375
|
+
|
|
2376
|
+
@example
|
|
2377
|
+
```
|
|
2378
|
+
import type {Paths} from 'type-fest';
|
|
2379
|
+
|
|
2380
|
+
type Project = {
|
|
2381
|
+
filename: string;
|
|
2382
|
+
listA: string[];
|
|
2383
|
+
listB: [{filename: string}];
|
|
2384
|
+
folder: {
|
|
2385
|
+
subfolder: {
|
|
2386
|
+
filename: string;
|
|
2387
|
+
};
|
|
2388
|
+
};
|
|
2389
|
+
};
|
|
2390
|
+
|
|
2391
|
+
type ProjectPaths = Paths<Project>;
|
|
2392
|
+
//=> 'filename' | 'listA' | 'listB' | 'folder' | `listA.${number}` | 'listB.0' | 'listB.0.filename' | 'folder.subfolder' | 'folder.subfolder.filename'
|
|
2393
|
+
|
|
2394
|
+
declare function open<Path extends ProjectPaths>(path: Path): void;
|
|
2395
|
+
|
|
2396
|
+
open('filename'); // Pass
|
|
2397
|
+
open('folder.subfolder'); // Pass
|
|
2398
|
+
open('folder.subfolder.filename'); // Pass
|
|
2399
|
+
// @ts-expect-error
|
|
2400
|
+
open('foo'); // TypeError
|
|
2401
|
+
|
|
2402
|
+
// Also works with arrays
|
|
2403
|
+
open('listA.1'); // Pass
|
|
2404
|
+
open('listB.0'); // Pass
|
|
2405
|
+
// @ts-expect-error
|
|
2406
|
+
open('listB.1'); // TypeError. Because listB only has one element.
|
|
2407
|
+
```
|
|
2408
|
+
|
|
2409
|
+
@category Object
|
|
2410
|
+
@category Array
|
|
2411
|
+
*/
|
|
2412
|
+
type Paths<T, Options extends PathsOptions = {}> = _Paths<T, ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, Options>>;
|
|
2413
|
+
type _Paths<T, Options extends Required<PathsOptions>, CurrentDepth extends number = 0> = T extends NonRecursiveType | Exclude<MapsSetsOrArrays, UnknownArray> ? never : IsAny<T> extends true ? never : T extends object ? InternalPaths<Required<T>, Options, CurrentDepth> : never;
|
|
2414
|
+
type InternalPaths<T, Options extends Required<PathsOptions>, CurrentDepth extends number> = { [Key in keyof T]: Key extends string | number // Limit `Key` to `string | number`
|
|
2415
|
+
? (And<Options['bracketNotation'], IsNumberLike<Key>> extends true ? `[${Key}]` : CurrentDepth extends 0 ?
|
|
2416
|
+
// Return both `Key` and `ToString<Key>` because for number keys, like `1`, both `1` and `'1'` are valid keys.
|
|
2417
|
+
Key | ToString<Key> : `.${(Key | ToString<Key>)}`) extends (infer TransformedKey extends string | number) ? ((Options['leavesOnly'] extends true ? Options['maxRecursionDepth'] extends CurrentDepth ? TransformedKey : IsNever<T[Key]> extends true ? TransformedKey : T[Key] extends (infer Value // For distributing `T[Key]`
|
|
2418
|
+
) ? (Value extends readonly [] | NonRecursiveType | Exclude<MapsSetsOrArrays, UnknownArray> ? TransformedKey : IsNever<keyof Value> extends true // Check for empty object & `unknown`, because `keyof unknown` is `never`.
|
|
2419
|
+
? TransformedKey : never) : never // Should never happen
|
|
2420
|
+
: TransformedKey) extends (infer _TransformedKey) ?
|
|
2421
|
+
// If `depth` is provided, the condition becomes truthy only when it matches `CurrentDepth`.
|
|
2422
|
+
// Otherwise, since `depth` defaults to `number`, the condition is always truthy, returning paths at all depths.
|
|
2423
|
+
CurrentDepth extends Options['depth'] ? _TransformedKey : never : never) |
|
|
2424
|
+
// Recursively generate paths for the current key
|
|
2425
|
+
(GreaterThan<Options['maxRecursionDepth'], CurrentDepth> extends true // Limit the depth to prevent infinite recursion
|
|
2426
|
+
? `${TransformedKey}${_Paths<T[Key], Options, Sum<CurrentDepth, 1>> & (string | number)}` : never) : never : never; }[keyof T & (T extends UnknownArray ? number : unknown)];
|
|
2427
|
+
/**
|
|
2428
|
+
Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.
|
|
2429
|
+
|
|
2430
|
+
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.
|
|
2431
|
+
|
|
2432
|
+
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.
|
|
2433
|
+
|
|
2434
|
+
@example
|
|
2435
|
+
```
|
|
2436
|
+
import type {LiteralUnion} from 'type-fest';
|
|
2437
|
+
|
|
2438
|
+
// Before
|
|
2439
|
+
|
|
2440
|
+
type Pet = 'dog' | 'cat' | string;
|
|
2441
|
+
|
|
2442
|
+
const petWithoutAutocomplete: Pet = '';
|
|
2443
|
+
// Start typing in your TypeScript-enabled IDE.
|
|
2444
|
+
// You **will not** get auto-completion for `dog` and `cat` literals.
|
|
2445
|
+
|
|
2446
|
+
// After
|
|
2447
|
+
|
|
2448
|
+
type Pet2 = LiteralUnion<'dog' | 'cat', string>;
|
|
2449
|
+
|
|
2450
|
+
const petWithAutoComplete: Pet2 = '';
|
|
2451
|
+
// You **will** get auto-completion for `dog` and `cat` literals.
|
|
2452
|
+
```
|
|
2453
|
+
|
|
2454
|
+
@category Type
|
|
2455
|
+
*/
|
|
2456
|
+
type LiteralUnion<LiteralType, BaseType extends Primitive> = LiteralType | (BaseType & Record<never, never>);
|
|
2457
|
+
declare namespace PackageJson$1 {
|
|
2458
|
+
/**
|
|
2459
|
+
A person who has been involved in creating or maintaining the package.
|
|
2460
|
+
*/
|
|
2461
|
+
type Person = string | {
|
|
2462
|
+
name: string;
|
|
2463
|
+
url?: string;
|
|
2464
|
+
email?: string;
|
|
2465
|
+
};
|
|
2466
|
+
type BugsLocation = string | {
|
|
2467
|
+
/**
|
|
2468
|
+
The URL to the package's issue tracker.
|
|
2469
|
+
*/
|
|
2470
|
+
url?: string;
|
|
2471
|
+
/**
|
|
2472
|
+
The email address to which issues should be reported.
|
|
2473
|
+
*/
|
|
2474
|
+
email?: string;
|
|
2475
|
+
};
|
|
2476
|
+
type DirectoryLocations = {
|
|
2477
|
+
[directoryType: string]: JsonValue | undefined;
|
|
2478
|
+
/**
|
|
2479
|
+
Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder.
|
|
2480
|
+
*/
|
|
2481
|
+
bin?: string;
|
|
2482
|
+
/**
|
|
2483
|
+
Location for Markdown files.
|
|
2484
|
+
*/
|
|
2485
|
+
doc?: string;
|
|
2486
|
+
/**
|
|
2487
|
+
Location for example scripts.
|
|
2488
|
+
*/
|
|
2489
|
+
example?: string;
|
|
2490
|
+
/**
|
|
2491
|
+
Location for the bulk of the library.
|
|
2492
|
+
*/
|
|
2493
|
+
lib?: string;
|
|
2494
|
+
/**
|
|
2495
|
+
Location for man pages. Sugar to generate a `man` array by walking the folder.
|
|
2496
|
+
*/
|
|
2497
|
+
man?: string;
|
|
2498
|
+
/**
|
|
2499
|
+
Location for test files.
|
|
2500
|
+
*/
|
|
2501
|
+
test?: string;
|
|
2502
|
+
};
|
|
2503
|
+
type Scripts = {
|
|
2504
|
+
/**
|
|
2505
|
+
Run **before** the package is published (Also run on local `npm install` without any arguments).
|
|
2506
|
+
*/
|
|
2507
|
+
prepublish?: string;
|
|
2508
|
+
/**
|
|
2509
|
+
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`.
|
|
2510
|
+
*/
|
|
2511
|
+
prepare?: string;
|
|
2512
|
+
/**
|
|
2513
|
+
Run **before** the package is prepared and packed, **only** on `npm publish`.
|
|
2514
|
+
*/
|
|
2515
|
+
prepublishOnly?: string;
|
|
2516
|
+
/**
|
|
2517
|
+
Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies).
|
|
2518
|
+
*/
|
|
2519
|
+
prepack?: string;
|
|
2520
|
+
/**
|
|
2521
|
+
Run **after** the tarball has been generated and moved to its final destination.
|
|
2522
|
+
*/
|
|
2523
|
+
postpack?: string;
|
|
2524
|
+
/**
|
|
2525
|
+
Run **after** the package is published.
|
|
2526
|
+
*/
|
|
2527
|
+
publish?: string;
|
|
2528
|
+
/**
|
|
2529
|
+
Run **after** the package is published.
|
|
2530
|
+
*/
|
|
2531
|
+
postpublish?: string;
|
|
2532
|
+
/**
|
|
2533
|
+
Run **before** the package is installed.
|
|
2534
|
+
*/
|
|
2535
|
+
preinstall?: string;
|
|
2536
|
+
/**
|
|
2537
|
+
Run **after** the package is installed.
|
|
2538
|
+
*/
|
|
2539
|
+
install?: string;
|
|
2540
|
+
/**
|
|
2541
|
+
Run **after** the package is installed and after `install`.
|
|
2542
|
+
*/
|
|
2543
|
+
postinstall?: string;
|
|
2544
|
+
/**
|
|
2545
|
+
Run **before** the package is uninstalled and before `uninstall`.
|
|
2546
|
+
*/
|
|
2547
|
+
preuninstall?: string;
|
|
2548
|
+
/**
|
|
2549
|
+
Run **before** the package is uninstalled.
|
|
2550
|
+
*/
|
|
2551
|
+
uninstall?: string;
|
|
2552
|
+
/**
|
|
2553
|
+
Run **after** the package is uninstalled.
|
|
2554
|
+
*/
|
|
2555
|
+
postuninstall?: string;
|
|
2556
|
+
/**
|
|
2557
|
+
Run **before** bump the package version and before `version`.
|
|
2558
|
+
*/
|
|
2559
|
+
preversion?: string;
|
|
2560
|
+
/**
|
|
2561
|
+
Run **before** bump the package version.
|
|
2562
|
+
*/
|
|
2563
|
+
version?: string;
|
|
2564
|
+
/**
|
|
2565
|
+
Run **after** bump the package version.
|
|
2566
|
+
*/
|
|
2567
|
+
postversion?: string;
|
|
2568
|
+
/**
|
|
2569
|
+
Run with the `npm test` command, before `test`.
|
|
2570
|
+
*/
|
|
2571
|
+
pretest?: string;
|
|
2572
|
+
/**
|
|
2573
|
+
Run with the `npm test` command.
|
|
2574
|
+
*/
|
|
2575
|
+
test?: string;
|
|
2576
|
+
/**
|
|
2577
|
+
Run with the `npm test` command, after `test`.
|
|
2578
|
+
*/
|
|
2579
|
+
posttest?: string;
|
|
2580
|
+
/**
|
|
2581
|
+
Run with the `npm stop` command, before `stop`.
|
|
2582
|
+
*/
|
|
2583
|
+
prestop?: string;
|
|
2584
|
+
/**
|
|
2585
|
+
Run with the `npm stop` command.
|
|
2586
|
+
*/
|
|
2587
|
+
stop?: string;
|
|
2588
|
+
/**
|
|
2589
|
+
Run with the `npm stop` command, after `stop`.
|
|
2590
|
+
*/
|
|
2591
|
+
poststop?: string;
|
|
2592
|
+
/**
|
|
2593
|
+
Run with the `npm start` command, before `start`.
|
|
2594
|
+
*/
|
|
2595
|
+
prestart?: string;
|
|
2596
|
+
/**
|
|
2597
|
+
Run with the `npm start` command.
|
|
2598
|
+
*/
|
|
2599
|
+
start?: string;
|
|
2600
|
+
/**
|
|
2601
|
+
Run with the `npm start` command, after `start`.
|
|
2602
|
+
*/
|
|
2603
|
+
poststart?: string;
|
|
2604
|
+
/**
|
|
2605
|
+
Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
|
|
2606
|
+
*/
|
|
2607
|
+
prerestart?: string;
|
|
2608
|
+
/**
|
|
2609
|
+
Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
|
|
2610
|
+
*/
|
|
2611
|
+
restart?: string;
|
|
2612
|
+
/**
|
|
2613
|
+
Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
|
|
2614
|
+
*/
|
|
2615
|
+
postrestart?: string;
|
|
2616
|
+
} & Partial<Record<string, string>>;
|
|
2617
|
+
/**
|
|
2618
|
+
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.
|
|
2619
|
+
*/
|
|
2620
|
+
type Dependency = Partial<Record<string, string>>;
|
|
2621
|
+
/**
|
|
2622
|
+
Recursive map describing selective dependency version overrides supported by npm.
|
|
2623
|
+
*/
|
|
2624
|
+
type DependencyOverrides = { [packageName in string]: string | undefined | DependencyOverrides; };
|
|
2625
|
+
/**
|
|
2626
|
+
Specifies requirements for development environment components such as operating systems, runtimes, or package managers. Used to ensure consistent development environments across the team.
|
|
2627
|
+
*/
|
|
2628
|
+
type DevEngineDependency = {
|
|
2629
|
+
name: string;
|
|
2630
|
+
version?: string;
|
|
2631
|
+
onFail?: 'ignore' | 'warn' | 'error' | 'download';
|
|
2632
|
+
};
|
|
2633
|
+
/**
|
|
2634
|
+
A mapping of conditions and the paths to which they resolve.
|
|
2635
|
+
*/
|
|
2636
|
+
type ExportConditions = {
|
|
2637
|
+
[condition: string]: Exports;
|
|
2638
|
+
};
|
|
2639
|
+
/**
|
|
2640
|
+
Entry points of a module, optionally with conditions and subpath exports.
|
|
2641
|
+
*/
|
|
2642
|
+
type Exports = null | string | Array<string | ExportConditions> | ExportConditions;
|
|
2643
|
+
/**
|
|
2644
|
+
Import map entries of a module, optionally with conditions and subpath imports.
|
|
2645
|
+
*/
|
|
2646
|
+
type Imports = {
|
|
2647
|
+
[key: `#${string}`]: Exports;
|
|
2648
|
+
};
|
|
2649
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
2650
|
+
interface NonStandardEntryPoints {
|
|
2651
|
+
/**
|
|
2652
|
+
An ECMAScript module ID that is the primary entry point to the program.
|
|
2653
|
+
*/
|
|
2654
|
+
module?: string;
|
|
2655
|
+
/**
|
|
2656
|
+
A module ID with untranspiled code that is the primary entry point to the program.
|
|
2657
|
+
*/
|
|
2658
|
+
esnext?: string | {
|
|
2659
|
+
[moduleName: string]: string | undefined;
|
|
2660
|
+
main?: string;
|
|
2661
|
+
browser?: string;
|
|
2662
|
+
};
|
|
2663
|
+
/**
|
|
2664
|
+
A hint to JavaScript bundlers or component tools when packaging modules for client side use.
|
|
2665
|
+
*/
|
|
2666
|
+
browser?: string | Partial<Record<string, string | false>>;
|
|
2667
|
+
/**
|
|
2668
|
+
Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused.
|
|
2669
|
+
|
|
2670
|
+
[Read more.](https://webpack.js.org/guides/tree-shaking/)
|
|
2671
|
+
*/
|
|
2672
|
+
sideEffects?: boolean | string[];
|
|
2673
|
+
}
|
|
2674
|
+
type TypeScriptConfiguration = {
|
|
2675
|
+
/**
|
|
2676
|
+
Location of the bundled TypeScript declaration file.
|
|
2677
|
+
*/
|
|
2678
|
+
types?: string;
|
|
2679
|
+
/**
|
|
2680
|
+
Version selection map of TypeScript.
|
|
2681
|
+
*/
|
|
2682
|
+
typesVersions?: Partial<Record<string, Partial<Record<string, string[]>>>>;
|
|
2683
|
+
/**
|
|
2684
|
+
Location of the bundled TypeScript declaration file. Alias of `types`.
|
|
2685
|
+
*/
|
|
2686
|
+
typings?: string;
|
|
2687
|
+
};
|
|
2688
|
+
/**
|
|
2689
|
+
An alternative configuration for workspaces.
|
|
2690
|
+
*/
|
|
2691
|
+
type WorkspaceConfig = {
|
|
2692
|
+
/**
|
|
2693
|
+
An array of workspace pattern strings which contain the workspace packages.
|
|
2694
|
+
*/
|
|
2695
|
+
packages?: WorkspacePattern[];
|
|
2696
|
+
/**
|
|
2697
|
+
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.
|
|
2698
|
+
|
|
2699
|
+
[Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn.
|
|
2700
|
+
[Not supported](https://github.com/npm/rfcs/issues/287) by npm.
|
|
2701
|
+
*/
|
|
2702
|
+
nohoist?: WorkspacePattern[];
|
|
2703
|
+
};
|
|
2704
|
+
/**
|
|
2705
|
+
A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process.
|
|
2706
|
+
|
|
2707
|
+
The patterns are handled with [minimatch](https://github.com/isaacs/minimatch).
|
|
2708
|
+
|
|
2709
|
+
@example
|
|
2710
|
+
`docs` → Include the docs directory and install its dependencies.
|
|
2711
|
+
`packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`.
|
|
2712
|
+
*/
|
|
2713
|
+
type WorkspacePattern = string;
|
|
2714
|
+
type YarnConfiguration = {
|
|
2715
|
+
/**
|
|
2716
|
+
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`.
|
|
2717
|
+
|
|
2718
|
+
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.
|
|
2719
|
+
*/
|
|
2720
|
+
flat?: boolean;
|
|
2721
|
+
/**
|
|
2722
|
+
Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file.
|
|
2723
|
+
*/
|
|
2724
|
+
resolutions?: Dependency;
|
|
2725
|
+
};
|
|
2726
|
+
type JSPMConfiguration = {
|
|
2727
|
+
/**
|
|
2728
|
+
JSPM configuration.
|
|
2729
|
+
*/
|
|
2730
|
+
jspm?: PackageJson$1;
|
|
2731
|
+
};
|
|
2732
|
+
/**
|
|
2733
|
+
Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties.
|
|
2734
|
+
*/
|
|
2735
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
2736
|
+
interface PackageJsonStandard {
|
|
2737
|
+
/**
|
|
2738
|
+
The name of the package.
|
|
2739
|
+
*/
|
|
2740
|
+
name?: string;
|
|
2741
|
+
/**
|
|
2742
|
+
Package version, parseable by [`node-semver`](https://github.com/npm/node-semver).
|
|
2743
|
+
*/
|
|
2744
|
+
version?: string;
|
|
2745
|
+
/**
|
|
2746
|
+
Package description, listed in `npm search`.
|
|
2747
|
+
*/
|
|
2748
|
+
description?: string;
|
|
2749
|
+
/**
|
|
2750
|
+
Keywords associated with package, listed in `npm search`.
|
|
2751
|
+
*/
|
|
2752
|
+
keywords?: string[];
|
|
2753
|
+
/**
|
|
2754
|
+
The URL to the package's homepage.
|
|
2755
|
+
*/
|
|
2756
|
+
homepage?: LiteralUnion<'.', string>;
|
|
2757
|
+
/**
|
|
2758
|
+
The URL to the package's issue tracker and/or the email address to which issues should be reported.
|
|
2759
|
+
*/
|
|
2760
|
+
bugs?: BugsLocation;
|
|
2761
|
+
/**
|
|
2762
|
+
The license for the package.
|
|
2763
|
+
*/
|
|
2764
|
+
license?: string;
|
|
2765
|
+
/**
|
|
2766
|
+
The licenses for the package.
|
|
2767
|
+
*/
|
|
2768
|
+
licenses?: Array<{
|
|
2769
|
+
type?: string;
|
|
2770
|
+
url?: string;
|
|
2771
|
+
}>;
|
|
2772
|
+
author?: Person;
|
|
2773
|
+
/**
|
|
2774
|
+
A list of people who contributed to the package.
|
|
2775
|
+
*/
|
|
2776
|
+
contributors?: Person[];
|
|
2777
|
+
/**
|
|
2778
|
+
A list of people who maintain the package.
|
|
2779
|
+
*/
|
|
2780
|
+
maintainers?: Person[];
|
|
2781
|
+
/**
|
|
2782
|
+
The files included in the package.
|
|
2783
|
+
*/
|
|
2784
|
+
files?: string[];
|
|
2785
|
+
/**
|
|
2786
|
+
Resolution algorithm for importing ".js" files from the package's scope.
|
|
2787
|
+
|
|
2788
|
+
[Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field)
|
|
2789
|
+
*/
|
|
2790
|
+
type?: 'module' | 'commonjs';
|
|
2791
|
+
/**
|
|
2792
|
+
The module ID that is the primary entry point to the program.
|
|
2793
|
+
*/
|
|
2794
|
+
main?: string;
|
|
2795
|
+
/**
|
|
2796
|
+
Subpath exports to define entry points of the package.
|
|
2797
|
+
|
|
2798
|
+
[Read more.](https://nodejs.org/api/packages.html#subpath-exports)
|
|
2799
|
+
*/
|
|
2800
|
+
exports?: Exports;
|
|
2801
|
+
/**
|
|
2802
|
+
Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself.
|
|
2803
|
+
|
|
2804
|
+
[Read more.](https://nodejs.org/api/packages.html#subpath-imports)
|
|
2805
|
+
*/
|
|
2806
|
+
imports?: Imports;
|
|
2807
|
+
/**
|
|
2808
|
+
The executable files that should be installed into the `PATH`.
|
|
2809
|
+
*/
|
|
2810
|
+
bin?: string | Partial<Record<string, string>>;
|
|
2811
|
+
/**
|
|
2812
|
+
Filenames to put in place for the `man` program to find.
|
|
2813
|
+
*/
|
|
2814
|
+
man?: string | string[];
|
|
2815
|
+
/**
|
|
2816
|
+
Indicates the structure of the package.
|
|
2817
|
+
*/
|
|
2818
|
+
directories?: DirectoryLocations;
|
|
2819
|
+
/**
|
|
2820
|
+
Location for the code repository.
|
|
2821
|
+
*/
|
|
2822
|
+
repository?: string | {
|
|
2823
|
+
type: string;
|
|
2824
|
+
url: string;
|
|
2825
|
+
/**
|
|
2826
|
+
Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo).
|
|
2827
|
+
|
|
2828
|
+
[Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md)
|
|
2829
|
+
*/
|
|
2830
|
+
directory?: string;
|
|
2831
|
+
};
|
|
2832
|
+
/**
|
|
2833
|
+
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.
|
|
2834
|
+
*/
|
|
2835
|
+
scripts?: Scripts;
|
|
2836
|
+
/**
|
|
2837
|
+
Is used to set configuration parameters used in package scripts that persist across upgrades.
|
|
2838
|
+
*/
|
|
2839
|
+
config?: JsonObject;
|
|
2840
|
+
/**
|
|
2841
|
+
The dependencies of the package.
|
|
2842
|
+
*/
|
|
2843
|
+
dependencies?: Dependency;
|
|
2844
|
+
/**
|
|
2845
|
+
Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling.
|
|
2846
|
+
*/
|
|
2847
|
+
devDependencies?: Dependency;
|
|
2848
|
+
/**
|
|
2849
|
+
Dependencies that are skipped if they fail to install.
|
|
2850
|
+
*/
|
|
2851
|
+
optionalDependencies?: Dependency;
|
|
2852
|
+
/**
|
|
2853
|
+
Dependencies that will usually be required by the package user directly or via another dependency.
|
|
2854
|
+
*/
|
|
2855
|
+
peerDependencies?: Dependency;
|
|
2856
|
+
/**
|
|
2857
|
+
Indicate peer dependencies that are optional.
|
|
2858
|
+
*/
|
|
2859
|
+
peerDependenciesMeta?: Partial<Record<string, {
|
|
2860
|
+
optional: true;
|
|
2861
|
+
}>>;
|
|
2862
|
+
/**
|
|
2863
|
+
Package names that are bundled when the package is published.
|
|
2864
|
+
*/
|
|
2865
|
+
bundledDependencies?: string[];
|
|
2866
|
+
/**
|
|
2867
|
+
Alias of `bundledDependencies`.
|
|
2868
|
+
*/
|
|
2869
|
+
bundleDependencies?: string[];
|
|
2870
|
+
/**
|
|
2871
|
+
Overrides is used to support selective version overrides using npm, which lets you define custom package versions or ranges inside your dependencies.
|
|
2872
|
+
*/
|
|
2873
|
+
overrides?: DependencyOverrides;
|
|
2874
|
+
/**
|
|
2875
|
+
Engines that this package runs on.
|
|
2876
|
+
*/
|
|
2877
|
+
engines?: { [EngineName in LiteralUnion<'npm' | 'node', string>]?: string; };
|
|
2878
|
+
/**
|
|
2879
|
+
@deprecated
|
|
2880
|
+
*/
|
|
2881
|
+
engineStrict?: boolean;
|
|
2882
|
+
/**
|
|
2883
|
+
Operating systems the module runs on.
|
|
2884
|
+
*/
|
|
2885
|
+
os?: Array<LiteralUnion<'aix' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32' | '!aix' | '!darwin' | '!freebsd' | '!linux' | '!openbsd' | '!sunos' | '!win32', string>>;
|
|
2886
|
+
/**
|
|
2887
|
+
CPU architectures the module runs on.
|
|
2888
|
+
*/
|
|
2889
|
+
cpu?: Array<LiteralUnion<'arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x32' | 'x64' | '!arm' | '!arm64' | '!ia32' | '!mips' | '!mipsel' | '!ppc' | '!ppc64' | '!s390' | '!s390x' | '!x32' | '!x64', string>>;
|
|
2890
|
+
/**
|
|
2891
|
+
Define the runtime and package manager for developing the current project.
|
|
2892
|
+
*/
|
|
2893
|
+
devEngines?: {
|
|
2894
|
+
os?: DevEngineDependency | DevEngineDependency[];
|
|
2895
|
+
cpu?: DevEngineDependency | DevEngineDependency[];
|
|
2896
|
+
libc?: DevEngineDependency | DevEngineDependency[];
|
|
2897
|
+
runtime?: DevEngineDependency | DevEngineDependency[];
|
|
2898
|
+
packageManager?: DevEngineDependency | DevEngineDependency[];
|
|
2899
|
+
};
|
|
2900
|
+
/**
|
|
2901
|
+
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.
|
|
2902
|
+
|
|
2903
|
+
@deprecated
|
|
2904
|
+
*/
|
|
2905
|
+
preferGlobal?: boolean;
|
|
2906
|
+
/**
|
|
2907
|
+
If set to `true`, then npm will refuse to publish it.
|
|
2908
|
+
*/
|
|
2909
|
+
private?: boolean;
|
|
2910
|
+
/**
|
|
2911
|
+
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.
|
|
2912
|
+
*/
|
|
2913
|
+
publishConfig?: PublishConfig;
|
|
2914
|
+
/**
|
|
2915
|
+
Describes and notifies consumers of a package's monetary support information.
|
|
2916
|
+
|
|
2917
|
+
[Read more.](https://github.com/npm/rfcs/blob/main/implemented/0017-add-funding-support.md)
|
|
2918
|
+
*/
|
|
2919
|
+
funding?: string | {
|
|
2920
|
+
/**
|
|
2921
|
+
The type of funding.
|
|
2922
|
+
*/
|
|
2923
|
+
type?: LiteralUnion<'github' | 'opencollective' | 'patreon' | 'individual' | 'foundation' | 'corporation', string>;
|
|
2924
|
+
/**
|
|
2925
|
+
The URL to the funding page.
|
|
2926
|
+
*/
|
|
2927
|
+
url: string;
|
|
2928
|
+
};
|
|
2929
|
+
/**
|
|
2930
|
+
Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/).
|
|
2931
|
+
|
|
2932
|
+
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.
|
|
2933
|
+
|
|
2934
|
+
Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces.
|
|
2935
|
+
*/
|
|
2936
|
+
workspaces?: WorkspacePattern[] | WorkspaceConfig;
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions).
|
|
2940
|
+
*/
|
|
2941
|
+
type NodeJsStandard = {
|
|
2942
|
+
/**
|
|
2943
|
+
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.
|
|
2944
|
+
|
|
2945
|
+
__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.__
|
|
2946
|
+
|
|
2947
|
+
@example
|
|
2948
|
+
```json
|
|
2949
|
+
{
|
|
2950
|
+
"packageManager": "<package manager name>@<version>"
|
|
2951
|
+
}
|
|
2952
|
+
```
|
|
2953
|
+
*/
|
|
2954
|
+
packageManager?: string;
|
|
2955
|
+
};
|
|
2956
|
+
type PublishConfig = {
|
|
2957
|
+
/**
|
|
2958
|
+
Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig).
|
|
2959
|
+
*/
|
|
2960
|
+
[additionalProperties: string]: JsonValue | undefined;
|
|
2961
|
+
/**
|
|
2962
|
+
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.
|
|
2963
|
+
*/
|
|
2964
|
+
access?: 'public' | 'restricted';
|
|
2965
|
+
/**
|
|
2966
|
+
The base URL of the npm registry.
|
|
2967
|
+
|
|
2968
|
+
Default: `'https://registry.npmjs.org/'`
|
|
2969
|
+
*/
|
|
2970
|
+
registry?: string;
|
|
2971
|
+
/**
|
|
2972
|
+
The tag to publish the package under.
|
|
2973
|
+
|
|
2974
|
+
Default: `'latest'`
|
|
2975
|
+
*/
|
|
2976
|
+
tag?: string;
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
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.
|
|
2981
|
+
|
|
2982
|
+
@category File
|
|
2983
|
+
*/
|
|
2984
|
+
type PackageJson$1 = JsonObject & PackageJson$1.NodeJsStandard & PackageJson$1.PackageJsonStandard & PackageJson$1.NonStandardEntryPoints & PackageJson$1.TypeScriptConfiguration & PackageJson$1.YarnConfiguration & PackageJson$1.JSPMConfiguration;
|
|
2985
|
+
type NormalizedPackageJson = Package & PackageJson;
|
|
2986
|
+
type PackageJson = PackageJson$1;
|
|
2987
|
+
type Cache<T = unknown> = Map<string, T>;
|
|
2988
|
+
type EnsurePackagesOptions = {
|
|
2989
|
+
/** Configuration for user confirmation prompts when installing packages */
|
|
2990
|
+
confirm?: {
|
|
2991
|
+
/** Default value for the confirmation prompt */
|
|
2992
|
+
default?: boolean;
|
|
2993
|
+
/** Message to display in the confirmation prompt, or a function that receives packages array */
|
|
2994
|
+
message: string | ((packages: string[]) => string);
|
|
2995
|
+
/**
|
|
2996
|
+
* Theme configuration for the prompt interface.
|
|
2997
|
+
* @deprecated Not implemented — the readline-based prompt ignores this option and uses
|
|
2998
|
+
* fixed styling. It will be removed in a future major release. Kept loosely typed so the
|
|
2999
|
+
* published declarations don't depend on `@inquirer/core`, which consumers never install.
|
|
3000
|
+
* `object` rather than a string-keyed record, because an interface-typed theme has no
|
|
3001
|
+
* index signature and so cannot satisfy the record form.
|
|
3002
|
+
*/
|
|
3003
|
+
theme?: object;
|
|
3004
|
+
/** Function to transform the boolean value for display */
|
|
3005
|
+
transformer?: (value: boolean) => string;
|
|
3006
|
+
};
|
|
3007
|
+
/** Current working directory for package operations */
|
|
3008
|
+
cwd?: URL | string;
|
|
3009
|
+
/** Whether to include regular dependencies in the operation */
|
|
3010
|
+
deps?: boolean;
|
|
3011
|
+
/** Whether to include development dependencies in the operation */
|
|
3012
|
+
devDeps?: boolean;
|
|
3013
|
+
/** Additional options for package installation (excluding cwd and dev which are handled separately) */
|
|
3014
|
+
installPackage?: Omit<InstallPackageOptions, "cwd" | "dev">;
|
|
3015
|
+
/** Custom logger interface for warning messages */
|
|
3016
|
+
logger?: {
|
|
3017
|
+
warn: (message: string) => void;
|
|
3018
|
+
};
|
|
3019
|
+
/** Whether to include peer dependencies in the operation */
|
|
3020
|
+
peerDeps?: boolean;
|
|
3021
|
+
/** Whether to throw an error when warnings are logged instead of just logging them */
|
|
3022
|
+
throwOnWarn?: boolean;
|
|
3023
|
+
};
|
|
3024
|
+
type ReadOptions = {
|
|
3025
|
+
cache?: FindPackageJsonCache | boolean;
|
|
3026
|
+
ignoreWarnings?: (RegExp | string)[];
|
|
3027
|
+
json5?: boolean;
|
|
3028
|
+
resolveCatalogs?: boolean;
|
|
3029
|
+
strict?: boolean;
|
|
3030
|
+
yaml?: boolean;
|
|
3031
|
+
};
|
|
3032
|
+
type FindPackageJsonCache = Cache<NormalizedReadResult>;
|
|
3033
|
+
type NormalizedReadResult = {
|
|
3034
|
+
packageJson: NormalizedPackageJson;
|
|
3035
|
+
path: string;
|
|
3036
|
+
};
|
|
3037
|
+
/**
|
|
3038
|
+
* An asynchronous function to find the package.json, package.yaml, or package.json5 file in the specified directory or its parent directories.
|
|
3039
|
+
* @param cwd The current working directory.
|
|
3040
|
+
* @param options Configuration options including yaml, json5, and resolveCatalogs flags.
|
|
3041
|
+
* @returns A `Promise` that resolves to an object containing the parsed package data and the file path.
|
|
3042
|
+
* The type of the returned promise is `Promise<NormalizedReadResult>`.
|
|
3043
|
+
* @throws {Error} If no package file can be found or if strict mode is enabled and normalize warnings are thrown.
|
|
3044
|
+
*/
|
|
3045
|
+
declare const findPackageJson: (cwd?: URL | string, options?: ReadOptions) => Promise<NormalizedReadResult>;
|
|
3046
|
+
/**
|
|
3047
|
+
* A synchronous function to find the package.json, package.yaml, or package.json5 file in the specified directory or its parent directories.
|
|
3048
|
+
* @param cwd The current working directory.
|
|
3049
|
+
* @param options Configuration options including yaml, json5, and resolveCatalogs flags.
|
|
3050
|
+
* @returns An object containing the parsed package data and the file path.
|
|
3051
|
+
* @throws {Error} If no package file can be found or if strict mode is enabled and normalize warnings are thrown.
|
|
3052
|
+
*/
|
|
3053
|
+
declare const findPackageJsonSync: (cwd?: URL | string, options?: ReadOptions) => NormalizedReadResult;
|
|
3054
|
+
/**
|
|
3055
|
+
* An asynchronous function to write the package.json file with the given data.
|
|
3056
|
+
* @param data The package.json data to write. The data is an intersection type of `PackageJson` and a record where keys are `string` and values can be any type.
|
|
3057
|
+
* @param options Optional. The options for writing the package.json. If not provided, an empty object will be used `{}`.
|
|
3058
|
+
* This is an intersection type of `WriteJsonOptions` and a record with an optional `cwd` key which type is `Options["cwd"]`.
|
|
3059
|
+
* `cwd` represents the current working directory. If not specified, the default working directory will be used.
|
|
3060
|
+
* @returns A `Promise` that resolves once the package.json file has been written. The type of the returned promise is `Promise<void>`.
|
|
3061
|
+
*/
|
|
3062
|
+
declare const writePackageJson: (data: PackageJson, options?: WriteJsonOptions & {
|
|
3063
|
+
cwd?: URL | string;
|
|
3064
|
+
}) => Promise<void>;
|
|
3065
|
+
declare const writePackageJsonSync: (data: PackageJson, options?: WriteJsonOptions & {
|
|
3066
|
+
cwd?: URL | string;
|
|
3067
|
+
}) => void;
|
|
3068
|
+
/**
|
|
3069
|
+
* Clears the module-level package.json file and parse caches.
|
|
3070
|
+
*
|
|
3071
|
+
* The caches populated by `findPackageJson[Sync]` / `parsePackageJson[Sync]` when
|
|
3072
|
+
* `cache: true` (and no custom cache is supplied) never expire on their own. Call this
|
|
3073
|
+
* to drop all cached reads — for example in long-running processes or tests that mutate
|
|
3074
|
+
* package files out of band.
|
|
3075
|
+
*/
|
|
3076
|
+
declare const clearPackageJsonCache: () => void;
|
|
3077
|
+
/**
|
|
3078
|
+
* A synchronous function to parse the package.json, package.yaml, or package.json5 file/object/string and return normalize the data.
|
|
3079
|
+
* @param packageFile
|
|
3080
|
+
* @param options
|
|
3081
|
+
* @param options.cache Cache for parsed results (only applies to file paths)
|
|
3082
|
+
* @param options.ignoreWarnings List of warning messages or patterns to skip in strict mode
|
|
3083
|
+
* @param options.resolveCatalogs Whether to resolve pnpm catalog references
|
|
3084
|
+
* @param options.strict Whether to throw errors on normalization warnings
|
|
3085
|
+
* @param options.yaml Whether to enable package.yaml parsing (default: true)
|
|
3086
|
+
* @param options.json5 Whether to enable package.json5 parsing (default: true)
|
|
3087
|
+
* @returns
|
|
3088
|
+
* @throws {Error} If the packageFile parameter is not an object or a string or if strict mode is enabled and normalize warnings are thrown.
|
|
3089
|
+
*/
|
|
3090
|
+
declare const parsePackageJsonSync: (packageFile: JsonObject | string, options?: {
|
|
3091
|
+
cache?: Cache<NormalizedPackageJson> | boolean;
|
|
3092
|
+
ignoreWarnings?: (RegExp | string)[];
|
|
3093
|
+
json5?: boolean;
|
|
3094
|
+
resolveCatalogs?: boolean;
|
|
3095
|
+
strict?: boolean;
|
|
3096
|
+
yaml?: boolean;
|
|
3097
|
+
}) => NormalizedPackageJson;
|
|
3098
|
+
/**
|
|
3099
|
+
* An asynchronous function to parse the package.json, package.yaml, or package.json5 file/object/string and return normalize the data.
|
|
3100
|
+
* @param packageFile
|
|
3101
|
+
* @param options
|
|
3102
|
+
* @param options.cache Cache for parsed results (only applies to file paths)
|
|
3103
|
+
* @param options.ignoreWarnings List of warning messages or patterns to skip in strict mode
|
|
3104
|
+
* @param options.strict Whether to throw errors on normalization warnings
|
|
3105
|
+
* @param options.resolveCatalogs Whether to resolve pnpm catalog references
|
|
3106
|
+
* @param options.yaml Whether to enable package.yaml parsing (default: true)
|
|
3107
|
+
* @param options.json5 Whether to enable package.json5 parsing (default: true)
|
|
3108
|
+
* @returns
|
|
3109
|
+
* @throws {Error} If the packageFile parameter is not an object or a string or if strict mode is enabled and normalize warnings are thrown.
|
|
3110
|
+
*/
|
|
3111
|
+
declare const parsePackageJson: (packageFile: JsonObject | string, options?: {
|
|
3112
|
+
cache?: Cache<NormalizedPackageJson> | boolean;
|
|
3113
|
+
ignoreWarnings?: (RegExp | string)[];
|
|
3114
|
+
json5?: boolean;
|
|
3115
|
+
resolveCatalogs?: boolean;
|
|
3116
|
+
strict?: boolean;
|
|
3117
|
+
yaml?: boolean;
|
|
3118
|
+
}) => Promise<NormalizedPackageJson>;
|
|
3119
|
+
/**
|
|
3120
|
+
* An asynchronous function to get the value of a property from the package.json file.
|
|
3121
|
+
* @param packageJson
|
|
3122
|
+
* @param property
|
|
3123
|
+
* @param defaultValue
|
|
3124
|
+
* @returns
|
|
3125
|
+
*/
|
|
3126
|
+
declare const getPackageJsonProperty: <T = unknown>(packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>, defaultValue?: T) => T;
|
|
3127
|
+
/**
|
|
3128
|
+
* An asynchronous function to check if a property exists in the package.json file.
|
|
3129
|
+
* @param packageJson
|
|
3130
|
+
* @param property
|
|
3131
|
+
* @returns
|
|
3132
|
+
*/
|
|
3133
|
+
declare const hasPackageJsonProperty: (packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>) => boolean;
|
|
3134
|
+
/**
|
|
3135
|
+
* An asynchronous function to check if any of the specified dependencies exist in the package.json file.
|
|
3136
|
+
* @param packageJson
|
|
3137
|
+
* @param arguments_
|
|
3138
|
+
* @param options
|
|
3139
|
+
* @param options.peerDeps Whether to include peer dependencies
|
|
3140
|
+
* @returns
|
|
3141
|
+
*/
|
|
3142
|
+
declare const hasPackageJsonAnyDependency: (packageJson: NormalizedPackageJson, arguments_: string[], options?: {
|
|
3143
|
+
peerDeps?: boolean;
|
|
3144
|
+
}) => boolean;
|
|
3145
|
+
/**
|
|
3146
|
+
* An asynchronous function to ensure that the specified packages are installed in the package.json file.
|
|
3147
|
+
* If the packages are not installed, the user will be prompted to install them.
|
|
3148
|
+
* If the user agrees, the packages will be installed.
|
|
3149
|
+
* If the user declines, the function will return without installing the packages.
|
|
3150
|
+
* If the user does not respond, the function will return without installing the packages.
|
|
3151
|
+
* @param packageJson
|
|
3152
|
+
* @param packages
|
|
3153
|
+
* @param installKey
|
|
3154
|
+
* @param options
|
|
3155
|
+
* @param options.deps Whether to include regular dependencies
|
|
3156
|
+
* @param options.devDeps Whether to include development dependencies
|
|
3157
|
+
* @param options.peerDeps Whether to include peer dependencies
|
|
3158
|
+
* @param options.throwOnWarn Whether to throw an error when warnings are logged instead of just logging them
|
|
3159
|
+
* @param options.logger Whether to use a custom logger
|
|
3160
|
+
* @param options.confirm Whether to use a custom confirmation prompt
|
|
3161
|
+
* @param options.installPackage Whether to use a custom installation package
|
|
3162
|
+
* @param options.cwd Whether to use a custom current working directory
|
|
3163
|
+
* @param options.dev Whether to use a custom installation key
|
|
3164
|
+
* @returns
|
|
3165
|
+
*/
|
|
3166
|
+
declare const ensurePackages: (packageJson: NormalizedPackageJson, packages: string[], installKey?: "dependencies" | "devDependencies", options?: EnsurePackagesOptions) => Promise<void>;
|
|
3167
|
+
export { EnsurePackagesOptions as E, FindPackageJsonCache as F, NormalizedPackageJson as N, PackageJson as P, NormalizedReadResult as a, findPackageJsonSync as b, clearPackageJsonCache as c, hasPackageJsonProperty as d, ensurePackages as e, findPackageJson as f, getPackageJsonProperty as g, hasPackageJsonAnyDependency as h, parsePackageJsonSync as i, writePackageJsonSync as j, parsePackageJson as p, writePackageJson as w };
|