@bemoje/cli 3.1.1 → 3.1.3
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/lib/index.cjs +75 -6192
- package/lib/index.d.cts +2658 -6
- package/lib/index.d.ts +2658 -6
- package/lib/index.js +71 -6190
- package/package.json +41 -113
- package/lib/lib/Command.cjs +0 -7626
- package/lib/lib/Command.d.cts +0 -1
- package/lib/lib/Command.d.ts +0 -1
- package/lib/lib/Command.js +0 -7620
- package/lib/lib/Help.cjs +0 -5201
- package/lib/lib/Help.d.cts +0 -1
- package/lib/lib/Help.d.ts +0 -1
- package/lib/lib/Help.js +0 -5195
- package/lib/lib/helpers/findCommand.cjs +0 -20
- package/lib/lib/helpers/findCommand.d.cts +0 -8
- package/lib/lib/helpers/findCommand.d.ts +0 -8
- package/lib/lib/helpers/findCommand.js +0 -18
- package/lib/lib/helpers/findOption.cjs +0 -18
- package/lib/lib/helpers/findOption.d.cts +0 -8
- package/lib/lib/helpers/findOption.d.ts +0 -8
- package/lib/lib/helpers/findOption.js +0 -16
- package/lib/lib/helpers/getCommandAncestors.cjs +0 -23
- package/lib/lib/helpers/getCommandAncestors.d.cts +0 -8
- package/lib/lib/helpers/getCommandAncestors.d.ts +0 -8
- package/lib/lib/helpers/getCommandAncestors.js +0 -21
- package/lib/lib/helpers/getCommandAndAncestors.cjs +0 -17
- package/lib/lib/helpers/getCommandAndAncestors.d.cts +0 -8
- package/lib/lib/helpers/getCommandAndAncestors.d.ts +0 -8
- package/lib/lib/helpers/getCommandAndAncestors.js +0 -15
- package/lib/lib/helpers/parseOptionFlags.cjs +0 -30
- package/lib/lib/helpers/parseOptionFlags.d.cts +0 -13
- package/lib/lib/helpers/parseOptionFlags.d.ts +0 -13
- package/lib/lib/helpers/parseOptionFlags.js +0 -28
- package/lib/lib/types.cjs +0 -2
- package/lib/lib/types.d.cts +0 -1
- package/lib/lib/types.d.ts +0 -1
- package/lib/lib/types.js +0 -1
package/lib/index.d.cts
CHANGED
|
@@ -1,6 +1,2658 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
/**
|
|
2
|
+
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
|
|
3
|
+
|
|
4
|
+
@category Type
|
|
5
|
+
*/
|
|
6
|
+
type Primitive =
|
|
7
|
+
| null
|
|
8
|
+
| undefined
|
|
9
|
+
| string
|
|
10
|
+
| number
|
|
11
|
+
| boolean
|
|
12
|
+
| symbol
|
|
13
|
+
| bigint;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
|
|
17
|
+
|
|
18
|
+
Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
|
|
19
|
+
|
|
20
|
+
@example
|
|
21
|
+
```
|
|
22
|
+
import type {UnionToIntersection} from 'type-fest';
|
|
23
|
+
|
|
24
|
+
type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
|
|
25
|
+
|
|
26
|
+
type Intersection = UnionToIntersection<Union>;
|
|
27
|
+
//=> {the(): void} & {great(arg: string): void} & {escape: boolean}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
@category Type
|
|
31
|
+
*/
|
|
32
|
+
type UnionToIntersection<Union> = (
|
|
33
|
+
// `extends unknown` is always going to be the case and is used to convert the
|
|
34
|
+
// `Union` into a [distributive conditional
|
|
35
|
+
// type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
|
|
36
|
+
Union extends unknown
|
|
37
|
+
// The union type is used as the only argument to a function since the union
|
|
38
|
+
// of function arguments is an intersection.
|
|
39
|
+
? (distributedUnion: Union) => void
|
|
40
|
+
// This won't happen.
|
|
41
|
+
: never
|
|
42
|
+
// Infer the `Intersection` type since TypeScript represents the positional
|
|
43
|
+
// arguments of unions of functions as an intersection of the union.
|
|
44
|
+
) extends ((mergedIntersection: infer Intersection) => void)
|
|
45
|
+
// The `& Union` is to ensure result of `UnionToIntersection<A | B>` is always assignable to `A | B`
|
|
46
|
+
? Intersection & Union
|
|
47
|
+
: never;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
Create a union of all keys from a given type, even those exclusive to specific union members.
|
|
51
|
+
|
|
52
|
+
Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
|
|
53
|
+
|
|
54
|
+
@link https://stackoverflow.com/a/49402091
|
|
55
|
+
|
|
56
|
+
@example
|
|
57
|
+
```
|
|
58
|
+
import type {KeysOfUnion} from 'type-fest';
|
|
59
|
+
|
|
60
|
+
type A = {
|
|
61
|
+
common: string;
|
|
62
|
+
a: number;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
type B = {
|
|
66
|
+
common: string;
|
|
67
|
+
b: string;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
type C = {
|
|
71
|
+
common: string;
|
|
72
|
+
c: boolean;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
type Union = A | B | C;
|
|
76
|
+
|
|
77
|
+
type CommonKeys = keyof Union;
|
|
78
|
+
//=> 'common'
|
|
79
|
+
|
|
80
|
+
type AllKeys = KeysOfUnion<Union>;
|
|
81
|
+
//=> 'common' | 'a' | 'b' | 'c'
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
@category Object
|
|
85
|
+
*/
|
|
86
|
+
type KeysOfUnion<ObjectType> =
|
|
87
|
+
// Hack to fix https://github.com/sindresorhus/type-fest/issues/1008
|
|
88
|
+
keyof UnionToIntersection<ObjectType extends unknown ? Record<keyof ObjectType, never> : never>;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
Returns a boolean for whether the given type is `any`.
|
|
92
|
+
|
|
93
|
+
@link https://stackoverflow.com/a/49928360/1490091
|
|
94
|
+
|
|
95
|
+
Useful in type utilities, such as disallowing `any`s to be passed to a function.
|
|
96
|
+
|
|
97
|
+
@example
|
|
98
|
+
```
|
|
99
|
+
import type {IsAny} from 'type-fest';
|
|
100
|
+
|
|
101
|
+
const typedObject = {a: 1, b: 2} as const;
|
|
102
|
+
const anyObject: any = {a: 1, b: 2};
|
|
103
|
+
|
|
104
|
+
function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(object: O, key: K) {
|
|
105
|
+
return object[key];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const typedA = get(typedObject, 'a');
|
|
109
|
+
//=> 1
|
|
110
|
+
|
|
111
|
+
const anyA = get(anyObject, 'a');
|
|
112
|
+
//=> any
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
@category Type Guard
|
|
116
|
+
@category Utilities
|
|
117
|
+
*/
|
|
118
|
+
type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
Returns a boolean for whether the given key is an optional key of type.
|
|
122
|
+
|
|
123
|
+
This is useful when writing utility types or schema validators that need to differentiate `optional` keys.
|
|
124
|
+
|
|
125
|
+
@example
|
|
126
|
+
```
|
|
127
|
+
import type {IsOptionalKeyOf} from 'type-fest';
|
|
128
|
+
|
|
129
|
+
type User = {
|
|
130
|
+
name: string;
|
|
131
|
+
surname: string;
|
|
132
|
+
|
|
133
|
+
luckyNumber?: number;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
type Admin = {
|
|
137
|
+
name: string;
|
|
138
|
+
surname?: string;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
type T1 = IsOptionalKeyOf<User, 'luckyNumber'>;
|
|
142
|
+
//=> true
|
|
143
|
+
|
|
144
|
+
type T2 = IsOptionalKeyOf<User, 'name'>;
|
|
145
|
+
//=> false
|
|
146
|
+
|
|
147
|
+
type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>;
|
|
148
|
+
//=> boolean
|
|
149
|
+
|
|
150
|
+
type T4 = IsOptionalKeyOf<User | Admin, 'name'>;
|
|
151
|
+
//=> false
|
|
152
|
+
|
|
153
|
+
type T5 = IsOptionalKeyOf<User | Admin, 'surname'>;
|
|
154
|
+
//=> boolean
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
@category Type Guard
|
|
158
|
+
@category Utilities
|
|
159
|
+
*/
|
|
160
|
+
type IsOptionalKeyOf<Type extends object, Key extends keyof Type> =
|
|
161
|
+
IsAny<Type | Key> extends true ? never
|
|
162
|
+
: Key extends keyof Type
|
|
163
|
+
? Type extends Record<Key, Type[Key]>
|
|
164
|
+
? false
|
|
165
|
+
: true
|
|
166
|
+
: false;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
Extract all optional keys from the given type.
|
|
170
|
+
|
|
171
|
+
This is useful when you want to create a new type that contains different type values for the optional keys only.
|
|
172
|
+
|
|
173
|
+
@example
|
|
174
|
+
```
|
|
175
|
+
import type {OptionalKeysOf, Except} from 'type-fest';
|
|
176
|
+
|
|
177
|
+
type User = {
|
|
178
|
+
name: string;
|
|
179
|
+
surname: string;
|
|
180
|
+
|
|
181
|
+
luckyNumber?: number;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const REMOVE_FIELD = Symbol('remove field symbol');
|
|
185
|
+
type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
|
|
186
|
+
[Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const update1: UpdateOperation<User> = {
|
|
190
|
+
name: 'Alice',
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const update2: UpdateOperation<User> = {
|
|
194
|
+
name: 'Bob',
|
|
195
|
+
luckyNumber: REMOVE_FIELD,
|
|
196
|
+
};
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
@category Utilities
|
|
200
|
+
*/
|
|
201
|
+
type OptionalKeysOf<Type extends object> =
|
|
202
|
+
Type extends unknown // For distributing `Type`
|
|
203
|
+
? (keyof {[Key in keyof Type as
|
|
204
|
+
IsOptionalKeyOf<Type, Key> extends false
|
|
205
|
+
? never
|
|
206
|
+
: Key
|
|
207
|
+
]: never
|
|
208
|
+
}) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf<Type>` is always assignable to `keyof Type`
|
|
209
|
+
: never; // Should never happen
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
Extract all required keys from the given type.
|
|
213
|
+
|
|
214
|
+
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...
|
|
215
|
+
|
|
216
|
+
@example
|
|
217
|
+
```
|
|
218
|
+
import type {RequiredKeysOf} from 'type-fest';
|
|
219
|
+
|
|
220
|
+
declare function createValidation<
|
|
221
|
+
Entity extends object,
|
|
222
|
+
Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>,
|
|
223
|
+
>(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean;
|
|
224
|
+
|
|
225
|
+
type User = {
|
|
226
|
+
name: string;
|
|
227
|
+
surname: string;
|
|
228
|
+
luckyNumber?: number;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const validator1 = createValidation<User>('name', value => value.length < 25);
|
|
232
|
+
const validator2 = createValidation<User>('surname', value => value.length < 25);
|
|
233
|
+
|
|
234
|
+
// @ts-expect-error
|
|
235
|
+
const validator3 = createValidation<User>('luckyNumber', value => value > 0);
|
|
236
|
+
// Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'.
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
@category Utilities
|
|
240
|
+
*/
|
|
241
|
+
type RequiredKeysOf<Type extends object> =
|
|
242
|
+
Type extends unknown // For distributing `Type`
|
|
243
|
+
? Exclude<keyof Type, OptionalKeysOf<Type>>
|
|
244
|
+
: never; // Should never happen
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
Returns a boolean for whether the given type is `never`.
|
|
248
|
+
|
|
249
|
+
@link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
|
|
250
|
+
@link https://stackoverflow.com/a/53984913/10292952
|
|
251
|
+
@link https://www.zhenghao.io/posts/ts-never
|
|
252
|
+
|
|
253
|
+
Useful in type utilities, such as checking if something does not occur.
|
|
254
|
+
|
|
255
|
+
@example
|
|
256
|
+
```
|
|
257
|
+
import type {IsNever, And} from 'type-fest';
|
|
258
|
+
|
|
259
|
+
type A = IsNever<never>;
|
|
260
|
+
//=> true
|
|
261
|
+
|
|
262
|
+
type B = IsNever<any>;
|
|
263
|
+
//=> false
|
|
264
|
+
|
|
265
|
+
type C = IsNever<unknown>;
|
|
266
|
+
//=> false
|
|
267
|
+
|
|
268
|
+
type D = IsNever<never[]>;
|
|
269
|
+
//=> false
|
|
270
|
+
|
|
271
|
+
type E = IsNever<object>;
|
|
272
|
+
//=> false
|
|
273
|
+
|
|
274
|
+
type F = IsNever<string>;
|
|
275
|
+
//=> false
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
@example
|
|
279
|
+
```
|
|
280
|
+
import type {IsNever} from 'type-fest';
|
|
281
|
+
|
|
282
|
+
type IsTrue<T> = T extends true ? true : false;
|
|
283
|
+
|
|
284
|
+
// When a distributive conditional is instantiated with `never`, the entire conditional results in `never`.
|
|
285
|
+
type A = IsTrue<never>;
|
|
286
|
+
//=> never
|
|
287
|
+
|
|
288
|
+
// If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional.
|
|
289
|
+
type IsTrueFixed<T> =
|
|
290
|
+
IsNever<T> extends true ? false : T extends true ? true : false;
|
|
291
|
+
|
|
292
|
+
type B = IsTrueFixed<never>;
|
|
293
|
+
//=> false
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
@category Type Guard
|
|
297
|
+
@category Utilities
|
|
298
|
+
*/
|
|
299
|
+
type IsNever<T> = [T] extends [never] ? true : false;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
|
|
303
|
+
|
|
304
|
+
Use-cases:
|
|
305
|
+
- 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'>`.
|
|
306
|
+
|
|
307
|
+
Note:
|
|
308
|
+
- 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'`.
|
|
309
|
+
- Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
|
|
310
|
+
|
|
311
|
+
@example
|
|
312
|
+
```
|
|
313
|
+
import type {If} from 'type-fest';
|
|
314
|
+
|
|
315
|
+
type A = If<true, 'yes', 'no'>;
|
|
316
|
+
//=> 'yes'
|
|
317
|
+
|
|
318
|
+
type B = If<false, 'yes', 'no'>;
|
|
319
|
+
//=> 'no'
|
|
320
|
+
|
|
321
|
+
type C = If<boolean, 'yes', 'no'>;
|
|
322
|
+
//=> 'yes' | 'no'
|
|
323
|
+
|
|
324
|
+
type D = If<any, 'yes', 'no'>;
|
|
325
|
+
//=> 'yes' | 'no'
|
|
326
|
+
|
|
327
|
+
type E = If<never, 'yes', 'no'>;
|
|
328
|
+
//=> 'no'
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
@example
|
|
332
|
+
```
|
|
333
|
+
import type {If, IsAny, IsNever} from 'type-fest';
|
|
334
|
+
|
|
335
|
+
type A = If<IsAny<unknown>, 'is any', 'not any'>;
|
|
336
|
+
//=> 'not any'
|
|
337
|
+
|
|
338
|
+
type B = If<IsNever<never>, 'is never', 'not never'>;
|
|
339
|
+
//=> 'is never'
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
@example
|
|
343
|
+
```
|
|
344
|
+
import type {If, IsEqual} from 'type-fest';
|
|
345
|
+
|
|
346
|
+
type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
|
|
347
|
+
|
|
348
|
+
type A = IfEqual<string, string, 'equal', 'not equal'>;
|
|
349
|
+
//=> 'equal'
|
|
350
|
+
|
|
351
|
+
type B = IfEqual<string, number, 'equal', 'not equal'>;
|
|
352
|
+
//=> 'not equal'
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
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:
|
|
356
|
+
|
|
357
|
+
@example
|
|
358
|
+
```
|
|
359
|
+
import type {If, IsEqual, StringRepeat} from 'type-fest';
|
|
360
|
+
|
|
361
|
+
type HundredZeroes = StringRepeat<'0', 100>;
|
|
362
|
+
|
|
363
|
+
// The following implementation is not tail recursive
|
|
364
|
+
type Includes<S extends string, Char extends string> =
|
|
365
|
+
S extends `${infer First}${infer Rest}`
|
|
366
|
+
? If<IsEqual<First, Char>,
|
|
367
|
+
'found',
|
|
368
|
+
Includes<Rest, Char>>
|
|
369
|
+
: 'not found';
|
|
370
|
+
|
|
371
|
+
// Hence, instantiations with long strings will fail
|
|
372
|
+
// @ts-expect-error
|
|
373
|
+
type Fails = Includes<HundredZeroes, '1'>;
|
|
374
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
375
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
376
|
+
|
|
377
|
+
// However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
|
|
378
|
+
type IncludesWithoutIf<S extends string, Char extends string> =
|
|
379
|
+
S extends `${infer First}${infer Rest}`
|
|
380
|
+
? IsEqual<First, Char> extends true
|
|
381
|
+
? 'found'
|
|
382
|
+
: IncludesWithoutIf<Rest, Char>
|
|
383
|
+
: 'not found';
|
|
384
|
+
|
|
385
|
+
// Now, instantiations with long strings will work
|
|
386
|
+
type Works = IncludesWithoutIf<HundredZeroes, '1'>;
|
|
387
|
+
//=> 'not found'
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
@category Type Guard
|
|
391
|
+
@category Utilities
|
|
392
|
+
*/
|
|
393
|
+
type If<Type extends boolean, IfBranch, ElseBranch> =
|
|
394
|
+
IsNever<Type> extends true
|
|
395
|
+
? ElseBranch
|
|
396
|
+
: Type extends true
|
|
397
|
+
? IfBranch
|
|
398
|
+
: ElseBranch;
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
Represents an array with `unknown` value.
|
|
402
|
+
|
|
403
|
+
Use case: You want a type that all arrays can be assigned to, but you don't care about the value.
|
|
404
|
+
|
|
405
|
+
@example
|
|
406
|
+
```
|
|
407
|
+
import type {UnknownArray} from 'type-fest';
|
|
408
|
+
|
|
409
|
+
type IsArray<T> = T extends UnknownArray ? true : false;
|
|
410
|
+
|
|
411
|
+
type A = IsArray<['foo']>;
|
|
412
|
+
//=> true
|
|
413
|
+
|
|
414
|
+
type B = IsArray<readonly number[]>;
|
|
415
|
+
//=> true
|
|
416
|
+
|
|
417
|
+
type C = IsArray<string>;
|
|
418
|
+
//=> false
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
@category Type
|
|
422
|
+
@category Array
|
|
423
|
+
*/
|
|
424
|
+
type UnknownArray = readonly unknown[];
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
Matches any primitive, `void`, `Date`, or `RegExp` value.
|
|
428
|
+
*/
|
|
429
|
+
type BuiltIns = Primitive | void | Date | RegExp;
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
Matches non-recursive types.
|
|
433
|
+
*/
|
|
434
|
+
type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown) | Promise<unknown>;
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
Returns a boolean for whether A is false.
|
|
438
|
+
|
|
439
|
+
@example
|
|
440
|
+
```
|
|
441
|
+
type A = Not<true>;
|
|
442
|
+
//=> false
|
|
443
|
+
|
|
444
|
+
type B = Not<false>;
|
|
445
|
+
//=> true
|
|
446
|
+
```
|
|
447
|
+
*/
|
|
448
|
+
type Not<A extends boolean> = A extends true
|
|
449
|
+
? false
|
|
450
|
+
: A extends false
|
|
451
|
+
? true
|
|
452
|
+
: never;
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
An if-else-like type that resolves depending on whether the given type is `any` or `never`.
|
|
456
|
+
|
|
457
|
+
@example
|
|
458
|
+
```
|
|
459
|
+
// When `T` is a NOT `any` or `never` (like `string`) => Returns `IfNotAnyOrNever` branch
|
|
460
|
+
type A = IfNotAnyOrNever<string, 'VALID', 'IS_ANY', 'IS_NEVER'>;
|
|
461
|
+
//=> 'VALID'
|
|
462
|
+
|
|
463
|
+
// When `T` is `any` => Returns `IfAny` branch
|
|
464
|
+
type B = IfNotAnyOrNever<any, 'VALID', 'IS_ANY', 'IS_NEVER'>;
|
|
465
|
+
//=> 'IS_ANY'
|
|
466
|
+
|
|
467
|
+
// When `T` is `never` => Returns `IfNever` branch
|
|
468
|
+
type C = IfNotAnyOrNever<never, 'VALID', 'IS_ANY', 'IS_NEVER'>;
|
|
469
|
+
//=> 'IS_NEVER'
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
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:
|
|
473
|
+
|
|
474
|
+
@example
|
|
475
|
+
```ts
|
|
476
|
+
import type {StringRepeat} from 'type-fest';
|
|
477
|
+
|
|
478
|
+
type NineHundredNinetyNineSpaces = StringRepeat<' ', 999>;
|
|
479
|
+
|
|
480
|
+
// The following implementation is not tail recursive
|
|
481
|
+
type TrimLeft<S extends string> = IfNotAnyOrNever<S, S extends ` ${infer R}` ? TrimLeft<R> : S>;
|
|
482
|
+
|
|
483
|
+
// Hence, instantiations with long strings will fail
|
|
484
|
+
// @ts-expect-error
|
|
485
|
+
type T1 = TrimLeft<NineHundredNinetyNineSpaces>;
|
|
486
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
487
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
488
|
+
|
|
489
|
+
// To fix this, move the recursion into a helper type
|
|
490
|
+
type TrimLeftOptimised<S extends string> = IfNotAnyOrNever<S, _TrimLeftOptimised<S>>;
|
|
491
|
+
|
|
492
|
+
type _TrimLeftOptimised<S extends string> = S extends ` ${infer R}` ? _TrimLeftOptimised<R> : S;
|
|
493
|
+
|
|
494
|
+
type T2 = TrimLeftOptimised<NineHundredNinetyNineSpaces>;
|
|
495
|
+
//=> ''
|
|
496
|
+
```
|
|
497
|
+
*/
|
|
498
|
+
type IfNotAnyOrNever<T, IfNotAnyOrNever, IfAny = any, IfNever = never> =
|
|
499
|
+
If<IsAny<T>, IfAny, If<IsNever<T>, IfNever, IfNotAnyOrNever>>;
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
Indicates the value of `exactOptionalPropertyTypes` compiler option.
|
|
503
|
+
*/
|
|
504
|
+
type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extends [string?]
|
|
505
|
+
? false
|
|
506
|
+
: true;
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
Returns whether the given array `T` is readonly.
|
|
510
|
+
*/
|
|
511
|
+
type IsArrayReadonly<T extends UnknownArray> = If<IsNever<T>, false, T extends unknown[] ? false : true>;
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
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.
|
|
515
|
+
|
|
516
|
+
@example
|
|
517
|
+
```
|
|
518
|
+
type A = CollapseRestElement<[string, string, ...number[]]>;
|
|
519
|
+
//=> [string, string, number]
|
|
520
|
+
|
|
521
|
+
type B = CollapseRestElement<[...string[], number, number]>;
|
|
522
|
+
//=> [string, number, number]
|
|
523
|
+
|
|
524
|
+
type C = CollapseRestElement<[string, string, ...Array<number | bigint>]>;
|
|
525
|
+
//=> [string, string, number | bigint]
|
|
526
|
+
|
|
527
|
+
type D = CollapseRestElement<[string, number]>;
|
|
528
|
+
//=> [string, number]
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
Note: Optional modifiers (`?`) are removed from elements unless the `exactOptionalPropertyTypes` compiler option is disabled. When disabled, there's an additional `| undefined` for optional elements.
|
|
532
|
+
|
|
533
|
+
@example
|
|
534
|
+
```
|
|
535
|
+
// `exactOptionalPropertyTypes` enabled
|
|
536
|
+
type A = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
537
|
+
//=> [string, string, number]
|
|
538
|
+
|
|
539
|
+
// `exactOptionalPropertyTypes` disabled
|
|
540
|
+
type B = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
541
|
+
//=> [string | undefined, string | undefined, number]
|
|
542
|
+
```
|
|
543
|
+
*/
|
|
544
|
+
type CollapseRestElement<TArray extends UnknownArray> = IfNotAnyOrNever<TArray, _CollapseRestElement<TArray>>;
|
|
545
|
+
|
|
546
|
+
type _CollapseRestElement<
|
|
547
|
+
TArray extends UnknownArray,
|
|
548
|
+
ForwardAccumulator extends UnknownArray = [],
|
|
549
|
+
BackwardAccumulator extends UnknownArray = [],
|
|
550
|
+
> =
|
|
551
|
+
TArray extends UnknownArray // For distributing `TArray`
|
|
552
|
+
? keyof TArray & `${number}` extends never
|
|
553
|
+
// Enters this branch, if `TArray` is empty (e.g., []),
|
|
554
|
+
// or `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
|
|
555
|
+
? TArray extends readonly [...infer Rest, infer Last]
|
|
556
|
+
? _CollapseRestElement<Rest, ForwardAccumulator, [Last, ...BackwardAccumulator]> // Accumulate elements that are present after the rest element.
|
|
557
|
+
: TArray extends readonly []
|
|
558
|
+
? [...ForwardAccumulator, ...BackwardAccumulator]
|
|
559
|
+
: [...ForwardAccumulator, TArray[number], ...BackwardAccumulator] // Add the rest element between the accumulated elements.
|
|
560
|
+
: TArray extends readonly [(infer First)?, ...infer Rest]
|
|
561
|
+
? _CollapseRestElement<
|
|
562
|
+
Rest,
|
|
563
|
+
[
|
|
564
|
+
...ForwardAccumulator,
|
|
565
|
+
'0' extends OptionalKeysOf<TArray>
|
|
566
|
+
? If<IsExactOptionalPropertyTypesEnabled, First, First | undefined> // Add `| undefined` for optional elements, if `exactOptionalPropertyTypes` is disabled.
|
|
567
|
+
: First,
|
|
568
|
+
],
|
|
569
|
+
BackwardAccumulator
|
|
570
|
+
>
|
|
571
|
+
: never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays.
|
|
572
|
+
: never; // Should never happen
|
|
573
|
+
|
|
574
|
+
type Whitespace =
|
|
575
|
+
| '\u{9}' // '\t'
|
|
576
|
+
| '\u{A}' // '\n'
|
|
577
|
+
| '\u{B}' // '\v'
|
|
578
|
+
| '\u{C}' // '\f'
|
|
579
|
+
| '\u{D}' // '\r'
|
|
580
|
+
| '\u{20}' // ' '
|
|
581
|
+
| '\u{85}'
|
|
582
|
+
| '\u{A0}'
|
|
583
|
+
| '\u{1680}'
|
|
584
|
+
| '\u{2000}'
|
|
585
|
+
| '\u{2001}'
|
|
586
|
+
| '\u{2002}'
|
|
587
|
+
| '\u{2003}'
|
|
588
|
+
| '\u{2004}'
|
|
589
|
+
| '\u{2005}'
|
|
590
|
+
| '\u{2006}'
|
|
591
|
+
| '\u{2007}'
|
|
592
|
+
| '\u{2008}'
|
|
593
|
+
| '\u{2009}'
|
|
594
|
+
| '\u{200A}'
|
|
595
|
+
| '\u{2028}'
|
|
596
|
+
| '\u{2029}'
|
|
597
|
+
| '\u{202F}'
|
|
598
|
+
| '\u{205F}'
|
|
599
|
+
| '\u{3000}'
|
|
600
|
+
| '\u{FEFF}';
|
|
601
|
+
|
|
602
|
+
type WordSeparators = '-' | '_' | Whitespace;
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
Remove spaces from the left side.
|
|
606
|
+
*/
|
|
607
|
+
type TrimLeft<V extends string> = V extends `${Whitespace}${infer R}` ? TrimLeft<R> : V;
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
Remove spaces from the right side.
|
|
611
|
+
*/
|
|
612
|
+
type TrimRight<V extends string> = V extends `${infer R}${Whitespace}` ? TrimRight<R> : V;
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
Remove leading and trailing spaces from a string.
|
|
616
|
+
|
|
617
|
+
@example
|
|
618
|
+
```
|
|
619
|
+
import type {Trim} from 'type-fest';
|
|
620
|
+
|
|
621
|
+
type Example = Trim<' foo '>;
|
|
622
|
+
//=> 'foo'
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
@category String
|
|
626
|
+
@category Template literal
|
|
627
|
+
*/
|
|
628
|
+
type Trim<V extends string> = TrimLeft<TrimRight<V>>;
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
Returns a boolean for whether the string is numeric.
|
|
632
|
+
|
|
633
|
+
This type is a workaround for [Microsoft/TypeScript#46109](https://github.com/microsoft/TypeScript/issues/46109#issuecomment-930307987).
|
|
634
|
+
*/
|
|
635
|
+
type IsNumeric<T extends string> = T extends `${number}`
|
|
636
|
+
? Trim<T> extends T
|
|
637
|
+
? true
|
|
638
|
+
: false
|
|
639
|
+
: false;
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
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.
|
|
643
|
+
|
|
644
|
+
@example
|
|
645
|
+
```
|
|
646
|
+
import type {Simplify} from 'type-fest';
|
|
647
|
+
|
|
648
|
+
type PositionProps = {
|
|
649
|
+
top: number;
|
|
650
|
+
left: number;
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
type SizeProps = {
|
|
654
|
+
width: number;
|
|
655
|
+
height: number;
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
// In your editor, hovering over `Props` will show a flattened object with all the properties.
|
|
659
|
+
type Props = Simplify<PositionProps & SizeProps>;
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
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.
|
|
663
|
+
|
|
664
|
+
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`.
|
|
665
|
+
|
|
666
|
+
@example
|
|
667
|
+
```
|
|
668
|
+
import type {Simplify} from 'type-fest';
|
|
669
|
+
|
|
670
|
+
interface SomeInterface {
|
|
671
|
+
foo: number;
|
|
672
|
+
bar?: string;
|
|
673
|
+
baz: number | undefined;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
type SomeType = {
|
|
677
|
+
foo: number;
|
|
678
|
+
bar?: string;
|
|
679
|
+
baz: number | undefined;
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
const literal = {foo: 123, bar: 'hello', baz: 456};
|
|
683
|
+
const someType: SomeType = literal;
|
|
684
|
+
const someInterface: SomeInterface = literal;
|
|
685
|
+
|
|
686
|
+
declare function fn(object: Record<string, unknown>): void;
|
|
687
|
+
|
|
688
|
+
fn(literal); // Good: literal object type is sealed
|
|
689
|
+
fn(someType); // Good: type is sealed
|
|
690
|
+
// @ts-expect-error
|
|
691
|
+
fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
|
|
692
|
+
fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
@link https://github.com/microsoft/TypeScript/issues/15300
|
|
696
|
+
@see {@link SimplifyDeep}
|
|
697
|
+
@category Object
|
|
698
|
+
*/
|
|
699
|
+
type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
Returns a boolean for whether the two given types are equal.
|
|
703
|
+
|
|
704
|
+
@link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
|
|
705
|
+
@link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
|
|
706
|
+
|
|
707
|
+
Use-cases:
|
|
708
|
+
- If you want to make a conditional branch based on the result of a comparison of two types.
|
|
709
|
+
|
|
710
|
+
@example
|
|
711
|
+
```
|
|
712
|
+
import type {IsEqual} from 'type-fest';
|
|
713
|
+
|
|
714
|
+
// This type returns a boolean for whether the given array includes the given item.
|
|
715
|
+
// `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
|
|
716
|
+
type Includes<Value extends readonly any[], Item> =
|
|
717
|
+
Value extends readonly [Value[0], ...infer rest]
|
|
718
|
+
? IsEqual<Value[0], Item> extends true
|
|
719
|
+
? true
|
|
720
|
+
: Includes<rest, Item>
|
|
721
|
+
: false;
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
@category Type Guard
|
|
725
|
+
@category Utilities
|
|
726
|
+
*/
|
|
727
|
+
type IsEqual<A, B> =
|
|
728
|
+
[A] extends [B]
|
|
729
|
+
? [B] extends [A]
|
|
730
|
+
? _IsEqual<A, B>
|
|
731
|
+
: false
|
|
732
|
+
: false;
|
|
733
|
+
|
|
734
|
+
// This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`.
|
|
735
|
+
type _IsEqual<A, B> =
|
|
736
|
+
(<G>() => G extends A & G | G ? 1 : 2) extends
|
|
737
|
+
(<G>() => G extends B & G | G ? 1 : 2)
|
|
738
|
+
? true
|
|
739
|
+
: false;
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
Omit any index signatures from the given object type, leaving only explicitly defined properties.
|
|
743
|
+
|
|
744
|
+
This is the counterpart of `PickIndexSignature`.
|
|
745
|
+
|
|
746
|
+
Use-cases:
|
|
747
|
+
- Remove overly permissive signatures from third-party types.
|
|
748
|
+
|
|
749
|
+
This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
750
|
+
|
|
751
|
+
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>`.
|
|
752
|
+
|
|
753
|
+
(The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
|
|
754
|
+
|
|
755
|
+
```
|
|
756
|
+
const indexed: Record<string, unknown> = {}; // Allowed
|
|
757
|
+
|
|
758
|
+
// @ts-expect-error
|
|
759
|
+
const keyed: Record<'foo', unknown> = {}; // Error
|
|
760
|
+
// TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
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:
|
|
764
|
+
|
|
765
|
+
```
|
|
766
|
+
type Indexed = {} extends Record<string, unknown>
|
|
767
|
+
? '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
768
|
+
: '❌ `{}` is NOT assignable to `Record<string, unknown>`';
|
|
769
|
+
|
|
770
|
+
type IndexedResult = Indexed;
|
|
771
|
+
//=> '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
772
|
+
|
|
773
|
+
type Keyed = {} extends Record<'foo' | 'bar', unknown>
|
|
774
|
+
? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', unknown>`'
|
|
775
|
+
: '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`';
|
|
776
|
+
|
|
777
|
+
type KeyedResult = Keyed;
|
|
778
|
+
//=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`'
|
|
779
|
+
```
|
|
780
|
+
|
|
781
|
+
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`...
|
|
782
|
+
|
|
783
|
+
```
|
|
784
|
+
type OmitIndexSignature<ObjectType> = {
|
|
785
|
+
[KeyType in keyof ObjectType // Map each key of `ObjectType`...
|
|
786
|
+
]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
|
|
787
|
+
};
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
|
|
791
|
+
|
|
792
|
+
```
|
|
793
|
+
type OmitIndexSignature<ObjectType> = {
|
|
794
|
+
[KeyType in keyof ObjectType
|
|
795
|
+
// Is `{}` assignable to `Record<KeyType, unknown>`?
|
|
796
|
+
as {} extends Record<KeyType, unknown>
|
|
797
|
+
? never // ✅ `{}` is assignable to `Record<KeyType, unknown>`
|
|
798
|
+
: KeyType // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
|
|
799
|
+
]: ObjectType[KeyType];
|
|
800
|
+
};
|
|
801
|
+
```
|
|
802
|
+
|
|
803
|
+
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.
|
|
804
|
+
|
|
805
|
+
@example
|
|
806
|
+
```
|
|
807
|
+
import type {OmitIndexSignature} from 'type-fest';
|
|
808
|
+
|
|
809
|
+
type Example = {
|
|
810
|
+
// These index signatures will be removed.
|
|
811
|
+
[x: string]: any;
|
|
812
|
+
[x: number]: any;
|
|
813
|
+
[x: symbol]: any;
|
|
814
|
+
[x: `head-${string}`]: string;
|
|
815
|
+
[x: `${string}-tail`]: string;
|
|
816
|
+
[x: `head-${string}-tail`]: string;
|
|
817
|
+
[x: `${bigint}`]: string;
|
|
818
|
+
[x: `embedded-${number}`]: string;
|
|
819
|
+
|
|
820
|
+
// These explicitly defined keys will remain.
|
|
821
|
+
foo: 'bar';
|
|
822
|
+
qux?: 'baz';
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
|
|
826
|
+
//=> {foo: 'bar'; qux?: 'baz'}
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
@see {@link PickIndexSignature}
|
|
830
|
+
@category Object
|
|
831
|
+
*/
|
|
832
|
+
type OmitIndexSignature<ObjectType> = {
|
|
833
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
|
|
834
|
+
? never
|
|
835
|
+
: KeyType]: ObjectType[KeyType];
|
|
836
|
+
};
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
Pick only index signatures from the given object type, leaving out all explicitly defined properties.
|
|
840
|
+
|
|
841
|
+
This is the counterpart of `OmitIndexSignature`.
|
|
842
|
+
|
|
843
|
+
@example
|
|
844
|
+
```
|
|
845
|
+
import type {PickIndexSignature} from 'type-fest';
|
|
846
|
+
|
|
847
|
+
declare const symbolKey: unique symbol;
|
|
848
|
+
|
|
849
|
+
type Example = {
|
|
850
|
+
// These index signatures will remain.
|
|
851
|
+
[x: string]: unknown;
|
|
852
|
+
[x: number]: unknown;
|
|
853
|
+
[x: symbol]: unknown;
|
|
854
|
+
[x: `head-${string}`]: string;
|
|
855
|
+
[x: `${string}-tail`]: string;
|
|
856
|
+
[x: `head-${string}-tail`]: string;
|
|
857
|
+
[x: `${bigint}`]: string;
|
|
858
|
+
[x: `embedded-${number}`]: string;
|
|
859
|
+
|
|
860
|
+
// These explicitly defined keys will be removed.
|
|
861
|
+
['kebab-case-key']: string;
|
|
862
|
+
[symbolKey]: string;
|
|
863
|
+
foo: 'bar';
|
|
864
|
+
qux?: 'baz';
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
type ExampleIndexSignature = PickIndexSignature<Example>;
|
|
868
|
+
// {
|
|
869
|
+
// [x: string]: unknown;
|
|
870
|
+
// [x: number]: unknown;
|
|
871
|
+
// [x: symbol]: unknown;
|
|
872
|
+
// [x: `head-${string}`]: string;
|
|
873
|
+
// [x: `${string}-tail`]: string;
|
|
874
|
+
// [x: `head-${string}-tail`]: string;
|
|
875
|
+
// [x: `${bigint}`]: string;
|
|
876
|
+
// [x: `embedded-${number}`]: string;
|
|
877
|
+
// }
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
@see {@link OmitIndexSignature}
|
|
881
|
+
@category Object
|
|
882
|
+
*/
|
|
883
|
+
type PickIndexSignature<ObjectType> = {
|
|
884
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
|
|
885
|
+
? KeyType
|
|
886
|
+
: never]: ObjectType[KeyType];
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
// Merges two objects without worrying about index signatures.
|
|
890
|
+
type SimpleMerge<Destination, Source> = Simplify<{
|
|
891
|
+
[Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
|
|
892
|
+
} & Source>;
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
Merge two types into a new type. Keys of the second type overrides keys of the first type.
|
|
896
|
+
|
|
897
|
+
@example
|
|
898
|
+
```
|
|
899
|
+
import type {Merge} from 'type-fest';
|
|
900
|
+
|
|
901
|
+
type Foo = {
|
|
902
|
+
[x: string]: unknown;
|
|
903
|
+
[x: number]: unknown;
|
|
904
|
+
foo: string;
|
|
905
|
+
bar: symbol;
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
type Bar = {
|
|
909
|
+
[x: number]: number;
|
|
910
|
+
[x: symbol]: unknown;
|
|
911
|
+
bar: Date;
|
|
912
|
+
baz: boolean;
|
|
913
|
+
};
|
|
914
|
+
|
|
915
|
+
export type FooBar = Merge<Foo, Bar>;
|
|
916
|
+
//=> {
|
|
917
|
+
// [x: string]: unknown;
|
|
918
|
+
// [x: number]: number;
|
|
919
|
+
// [x: symbol]: unknown;
|
|
920
|
+
// foo: string;
|
|
921
|
+
// bar: Date;
|
|
922
|
+
// baz: boolean;
|
|
923
|
+
// }
|
|
924
|
+
```
|
|
925
|
+
|
|
926
|
+
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.
|
|
927
|
+
|
|
928
|
+
@see {@link ObjectMerge}
|
|
929
|
+
@category Object
|
|
930
|
+
*/
|
|
931
|
+
type Merge<Destination, Source> =
|
|
932
|
+
Destination extends unknown // For distributing `Destination`
|
|
933
|
+
? Source extends unknown // For distributing `Source`
|
|
934
|
+
? If<IsEqual<Destination, Source>, Destination, _Merge<Destination, Source>>
|
|
935
|
+
: never // Should never happen
|
|
936
|
+
: never; // Should never happen
|
|
937
|
+
|
|
938
|
+
type _Merge<Destination, Source> =
|
|
939
|
+
Simplify<
|
|
940
|
+
SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
|
|
941
|
+
& SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
|
|
942
|
+
>;
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
Works similar to the built-in `Pick` utility type, except for the following differences:
|
|
946
|
+
- Distributes over union types and allows picking keys from any member of the union type.
|
|
947
|
+
- Primitives types are returned as-is.
|
|
948
|
+
- Picks all keys if `Keys` is `any`.
|
|
949
|
+
- Doesn't pick `number` from a `string` index signature.
|
|
950
|
+
|
|
951
|
+
@example
|
|
952
|
+
```
|
|
953
|
+
type ImageUpload = {
|
|
954
|
+
url: string;
|
|
955
|
+
size: number;
|
|
956
|
+
thumbnailUrl: string;
|
|
957
|
+
};
|
|
958
|
+
|
|
959
|
+
type VideoUpload = {
|
|
960
|
+
url: string;
|
|
961
|
+
duration: number;
|
|
962
|
+
encodingFormat: string;
|
|
963
|
+
};
|
|
964
|
+
|
|
965
|
+
// Distributes over union types and allows picking keys from any member of the union type
|
|
966
|
+
type MediaDisplay = HomomorphicPick<ImageUpload | VideoUpload, "url" | "size" | "duration">;
|
|
967
|
+
//=> {url: string; size: number} | {url: string; duration: number}
|
|
968
|
+
|
|
969
|
+
// Primitive types are returned as-is
|
|
970
|
+
type Primitive = HomomorphicPick<string | number, 'toUpperCase' | 'toString'>;
|
|
971
|
+
//=> string | number
|
|
972
|
+
|
|
973
|
+
// Picks all keys if `Keys` is `any`
|
|
974
|
+
type Any = HomomorphicPick<{a: 1; b: 2} | {c: 3}, any>;
|
|
975
|
+
//=> {a: 1; b: 2} | {c: 3}
|
|
976
|
+
|
|
977
|
+
// Doesn't pick `number` from a `string` index signature
|
|
978
|
+
type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>;
|
|
979
|
+
//=> {}
|
|
980
|
+
*/
|
|
981
|
+
type HomomorphicPick<T, Keys extends KeysOfUnion<T>> = {
|
|
982
|
+
[P in keyof T as Extract<P, Keys>]: T[P]
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
/**
|
|
986
|
+
Extract all possible values for a given key from a union of object types.
|
|
987
|
+
|
|
988
|
+
@example
|
|
989
|
+
```
|
|
990
|
+
type Statuses = ValueOfUnion<{id: 1; status: 'open'} | {id: 2; status: 'closed'}, 'status'>;
|
|
991
|
+
//=> "open" | "closed"
|
|
992
|
+
```
|
|
993
|
+
*/
|
|
994
|
+
type ValueOfUnion<Union, Key extends KeysOfUnion<Union>> =
|
|
995
|
+
Union extends unknown ? Key extends keyof Union ? Union[Key] : never : never;
|
|
996
|
+
|
|
997
|
+
/**
|
|
998
|
+
Extract all readonly keys from a union of object types.
|
|
999
|
+
|
|
1000
|
+
@example
|
|
1001
|
+
```
|
|
1002
|
+
type User = {
|
|
1003
|
+
readonly id: string;
|
|
1004
|
+
name: string;
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
type Post = {
|
|
1008
|
+
readonly id: string;
|
|
1009
|
+
readonly author: string;
|
|
1010
|
+
body: string;
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
type ReadonlyKeys = ReadonlyKeysOfUnion<User | Post>;
|
|
1014
|
+
//=> "id" | "author"
|
|
1015
|
+
```
|
|
1016
|
+
*/
|
|
1017
|
+
type ReadonlyKeysOfUnion<Union> = Union extends unknown ? keyof {
|
|
1018
|
+
[Key in keyof Union as IsEqual<{[K in Key]: Union[Key]}, {readonly [K in Key]: Union[Key]}> extends true ? Key : never]: never
|
|
1019
|
+
} : never;
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
Merges user specified options with default options.
|
|
1023
|
+
|
|
1024
|
+
@example
|
|
1025
|
+
```
|
|
1026
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1027
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
1028
|
+
type SpecifiedOptions = {leavesOnly: true};
|
|
1029
|
+
|
|
1030
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1031
|
+
//=> {maxRecursionDepth: 10; leavesOnly: true}
|
|
1032
|
+
```
|
|
1033
|
+
|
|
1034
|
+
@example
|
|
1035
|
+
```
|
|
1036
|
+
// Complains if default values are not provided for optional options
|
|
1037
|
+
|
|
1038
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1039
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10};
|
|
1040
|
+
type SpecifiedOptions = {};
|
|
1041
|
+
|
|
1042
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1043
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
1044
|
+
// Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
|
|
1045
|
+
```
|
|
1046
|
+
|
|
1047
|
+
@example
|
|
1048
|
+
```
|
|
1049
|
+
// Complains if an option's default type does not conform to the expected type
|
|
1050
|
+
|
|
1051
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1052
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
|
|
1053
|
+
type SpecifiedOptions = {};
|
|
1054
|
+
|
|
1055
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1056
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
1057
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
1058
|
+
```
|
|
1059
|
+
|
|
1060
|
+
@example
|
|
1061
|
+
```
|
|
1062
|
+
// Complains if an option's specified type does not conform to the expected type
|
|
1063
|
+
|
|
1064
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1065
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
1066
|
+
type SpecifiedOptions = {leavesOnly: 'yes'};
|
|
1067
|
+
|
|
1068
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
1069
|
+
// ~~~~~~~~~~~~~~~~
|
|
1070
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
1071
|
+
```
|
|
1072
|
+
*/
|
|
1073
|
+
type ApplyDefaultOptions<
|
|
1074
|
+
Options extends object,
|
|
1075
|
+
Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
|
|
1076
|
+
SpecifiedOptions extends Options,
|
|
1077
|
+
> =
|
|
1078
|
+
If<IsAny<SpecifiedOptions>, Defaults,
|
|
1079
|
+
If<IsNever<SpecifiedOptions>, Defaults,
|
|
1080
|
+
Simplify<Merge<Defaults, {
|
|
1081
|
+
[Key in keyof SpecifiedOptions
|
|
1082
|
+
as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key
|
|
1083
|
+
]: SpecifiedOptions[Key]
|
|
1084
|
+
}> & Required<Options>>>>;
|
|
1085
|
+
|
|
1086
|
+
/**
|
|
1087
|
+
Returns a boolean for whether either of two given types is true.
|
|
1088
|
+
|
|
1089
|
+
Use-case: Constructing complex conditional types where at least one condition must be satisfied.
|
|
1090
|
+
|
|
1091
|
+
@example
|
|
1092
|
+
```
|
|
1093
|
+
import type {Or} from 'type-fest';
|
|
1094
|
+
|
|
1095
|
+
type TT = Or<true, true>;
|
|
1096
|
+
//=> true
|
|
1097
|
+
|
|
1098
|
+
type TF = Or<true, false>;
|
|
1099
|
+
//=> true
|
|
1100
|
+
|
|
1101
|
+
type FT = Or<false, true>;
|
|
1102
|
+
//=> true
|
|
1103
|
+
|
|
1104
|
+
type FF = Or<false, false>;
|
|
1105
|
+
//=> false
|
|
1106
|
+
```
|
|
1107
|
+
|
|
1108
|
+
Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1109
|
+
For example, `Or<false, boolean>` expands to `Or<false, true> | Or<false, false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
1110
|
+
|
|
1111
|
+
@example
|
|
1112
|
+
```
|
|
1113
|
+
import type {Or} from 'type-fest';
|
|
1114
|
+
|
|
1115
|
+
type A = Or<false, boolean>;
|
|
1116
|
+
//=> boolean
|
|
1117
|
+
|
|
1118
|
+
type B = Or<boolean, false>;
|
|
1119
|
+
//=> boolean
|
|
1120
|
+
|
|
1121
|
+
type C = Or<true, boolean>;
|
|
1122
|
+
//=> true
|
|
1123
|
+
|
|
1124
|
+
type D = Or<boolean, true>;
|
|
1125
|
+
//=> true
|
|
1126
|
+
|
|
1127
|
+
type E = Or<boolean, boolean>;
|
|
1128
|
+
//=> boolean
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
Note: If `never` is passed as an argument, it is treated as `false` and the result is computed accordingly.
|
|
1132
|
+
|
|
1133
|
+
@example
|
|
1134
|
+
```
|
|
1135
|
+
import type {Or} from 'type-fest';
|
|
1136
|
+
|
|
1137
|
+
type A = Or<true, never>;
|
|
1138
|
+
//=> true
|
|
1139
|
+
|
|
1140
|
+
type B = Or<never, true>;
|
|
1141
|
+
//=> true
|
|
1142
|
+
|
|
1143
|
+
type C = Or<false, never>;
|
|
1144
|
+
//=> false
|
|
1145
|
+
|
|
1146
|
+
type D = Or<never, false>;
|
|
1147
|
+
//=> false
|
|
1148
|
+
|
|
1149
|
+
type E = Or<boolean, never>;
|
|
1150
|
+
//=> boolean
|
|
1151
|
+
|
|
1152
|
+
type F = Or<never, boolean>;
|
|
1153
|
+
//=> boolean
|
|
1154
|
+
|
|
1155
|
+
type G = Or<never, never>;
|
|
1156
|
+
//=> false
|
|
1157
|
+
```
|
|
1158
|
+
|
|
1159
|
+
@see {@link And}
|
|
1160
|
+
@see {@link Xor}
|
|
1161
|
+
*/
|
|
1162
|
+
type Or<A extends boolean, B extends boolean> =
|
|
1163
|
+
_Or<If<IsNever<A>, false, A>, If<IsNever<B>, false, B>>; // `never` is treated as `false`
|
|
1164
|
+
|
|
1165
|
+
type _Or<A extends boolean, B extends boolean> = A extends true
|
|
1166
|
+
? true
|
|
1167
|
+
: B extends true
|
|
1168
|
+
? true
|
|
1169
|
+
: false;
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
@see {@link AllExtend}
|
|
1173
|
+
*/
|
|
1174
|
+
type AllExtendOptions = {
|
|
1175
|
+
/**
|
|
1176
|
+
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
1177
|
+
|
|
1178
|
+
- 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`).
|
|
1179
|
+
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
1180
|
+
|
|
1181
|
+
@default true
|
|
1182
|
+
|
|
1183
|
+
@example
|
|
1184
|
+
```
|
|
1185
|
+
import type {AllExtend} from 'type-fest';
|
|
1186
|
+
|
|
1187
|
+
type A = AllExtend<[1, 2, never], number, {strictNever: true}>;
|
|
1188
|
+
//=> false
|
|
1189
|
+
|
|
1190
|
+
type B = AllExtend<[1, 2, never], number, {strictNever: false}>;
|
|
1191
|
+
//=> true
|
|
1192
|
+
|
|
1193
|
+
type C = AllExtend<[never, never], never, {strictNever: true}>;
|
|
1194
|
+
//=> true
|
|
1195
|
+
|
|
1196
|
+
type D = AllExtend<[never, never], never, {strictNever: false}>;
|
|
1197
|
+
//=> true
|
|
1198
|
+
|
|
1199
|
+
type E = AllExtend<['a', 'b', never], any, {strictNever: true}>;
|
|
1200
|
+
//=> true
|
|
1201
|
+
|
|
1202
|
+
type F = AllExtend<['a', 'b', never], any, {strictNever: false}>;
|
|
1203
|
+
//=> true
|
|
1204
|
+
|
|
1205
|
+
type G = AllExtend<[never, 1], never, {strictNever: true}>;
|
|
1206
|
+
//=> false
|
|
1207
|
+
|
|
1208
|
+
type H = AllExtend<[never, 1], never, {strictNever: false}>;
|
|
1209
|
+
//=> false
|
|
1210
|
+
```
|
|
1211
|
+
*/
|
|
1212
|
+
strictNever?: boolean;
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
type DefaultAllExtendOptions = {
|
|
1216
|
+
strictNever: true;
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
Returns a boolean for whether every element in an array type extends another type.
|
|
1221
|
+
|
|
1222
|
+
@example
|
|
1223
|
+
```
|
|
1224
|
+
import type {AllExtend} from 'type-fest';
|
|
1225
|
+
|
|
1226
|
+
type A = AllExtend<[1, 2, 3], number>;
|
|
1227
|
+
//=> true
|
|
1228
|
+
|
|
1229
|
+
type B = AllExtend<[1, 2, '3'], number>;
|
|
1230
|
+
//=> false
|
|
1231
|
+
|
|
1232
|
+
type C = AllExtend<[number, number | string], number>;
|
|
1233
|
+
//=> boolean
|
|
1234
|
+
|
|
1235
|
+
type D = AllExtend<[true, boolean, true], true>;
|
|
1236
|
+
//=> boolean
|
|
1237
|
+
```
|
|
1238
|
+
|
|
1239
|
+
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.
|
|
1240
|
+
|
|
1241
|
+
```
|
|
1242
|
+
// @exactOptionalPropertyTypes: true
|
|
1243
|
+
import type {AllExtend} from 'type-fest';
|
|
1244
|
+
|
|
1245
|
+
type A = AllExtend<[1?, 2?, 3?], number>;
|
|
1246
|
+
//=> true
|
|
1247
|
+
```
|
|
1248
|
+
|
|
1249
|
+
```
|
|
1250
|
+
// @exactOptionalPropertyTypes: false
|
|
1251
|
+
import type {AllExtend} from 'type-fest';
|
|
1252
|
+
|
|
1253
|
+
type A = AllExtend<[1?, 2?, 3?], number>;
|
|
1254
|
+
//=> boolean
|
|
1255
|
+
|
|
1256
|
+
type B = AllExtend<[1?, 2?, 3?], number | undefined>;
|
|
1257
|
+
//=> true
|
|
1258
|
+
```
|
|
1259
|
+
|
|
1260
|
+
@see {@link AllExtendOptions}
|
|
1261
|
+
|
|
1262
|
+
@category Utilities
|
|
1263
|
+
@category Array
|
|
1264
|
+
*/
|
|
1265
|
+
type AllExtend<TArray extends UnknownArray, Type, Options extends AllExtendOptions = {}> =
|
|
1266
|
+
_AllExtend<CollapseRestElement<TArray>, Type, ApplyDefaultOptions<AllExtendOptions, DefaultAllExtendOptions, Options>>;
|
|
1267
|
+
|
|
1268
|
+
type _AllExtend<TArray extends UnknownArray, Type, Options extends Required<AllExtendOptions>> = IfNotAnyOrNever<TArray, If<IsAny<Type>, true,
|
|
1269
|
+
TArray extends readonly [infer First, ...infer Rest]
|
|
1270
|
+
? IsNever<First> extends true
|
|
1271
|
+
? Or<IsNever<Type>, Not<Options['strictNever']>> extends true
|
|
1272
|
+
// If target `Type` is also `never` OR `strictNever` is disabled, recurse further.
|
|
1273
|
+
? _AllExtend<Rest, Type, Options>
|
|
1274
|
+
: false
|
|
1275
|
+
: First extends Type
|
|
1276
|
+
? _AllExtend<Rest, Type, Options>
|
|
1277
|
+
: false
|
|
1278
|
+
: true
|
|
1279
|
+
>, false, false>;
|
|
1280
|
+
|
|
1281
|
+
/**
|
|
1282
|
+
Filter out keys from an object.
|
|
1283
|
+
|
|
1284
|
+
Returns `never` if `Exclude` is strictly equal to `Key`.
|
|
1285
|
+
Returns `never` if `Key` extends `Exclude`.
|
|
1286
|
+
Returns `Key` otherwise.
|
|
1287
|
+
|
|
1288
|
+
@example
|
|
1289
|
+
```
|
|
1290
|
+
type Filtered = Filter<'foo', 'foo'>;
|
|
1291
|
+
//=> never
|
|
1292
|
+
```
|
|
1293
|
+
|
|
1294
|
+
@example
|
|
1295
|
+
```
|
|
1296
|
+
type Filtered = Filter<'bar', string>;
|
|
1297
|
+
//=> never
|
|
1298
|
+
```
|
|
1299
|
+
|
|
1300
|
+
@example
|
|
1301
|
+
```
|
|
1302
|
+
type Filtered = Filter<'bar', 'foo'>;
|
|
1303
|
+
//=> 'bar'
|
|
1304
|
+
```
|
|
1305
|
+
|
|
1306
|
+
@see {Except}
|
|
1307
|
+
*/
|
|
1308
|
+
type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType);
|
|
1309
|
+
|
|
1310
|
+
type ExceptOptions = {
|
|
1311
|
+
/**
|
|
1312
|
+
Disallow assigning non-specified properties.
|
|
1313
|
+
|
|
1314
|
+
Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.
|
|
1315
|
+
|
|
1316
|
+
@default false
|
|
1317
|
+
*/
|
|
1318
|
+
requireExactProps?: boolean;
|
|
1319
|
+
};
|
|
1320
|
+
|
|
1321
|
+
type DefaultExceptOptions = {
|
|
1322
|
+
requireExactProps: false;
|
|
1323
|
+
};
|
|
1324
|
+
|
|
1325
|
+
/**
|
|
1326
|
+
Create a type from an object type without certain keys.
|
|
1327
|
+
|
|
1328
|
+
We recommend setting the `requireExactProps` option to `true`.
|
|
1329
|
+
|
|
1330
|
+
This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
|
|
1331
|
+
|
|
1332
|
+
This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
|
|
1333
|
+
|
|
1334
|
+
@example
|
|
1335
|
+
```
|
|
1336
|
+
import type {Except} from 'type-fest';
|
|
1337
|
+
|
|
1338
|
+
type Foo = {
|
|
1339
|
+
a: number;
|
|
1340
|
+
b: string;
|
|
1341
|
+
};
|
|
1342
|
+
|
|
1343
|
+
type FooWithoutA = Except<Foo, 'a'>;
|
|
1344
|
+
//=> {b: string}
|
|
1345
|
+
|
|
1346
|
+
// @ts-expect-error
|
|
1347
|
+
const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
|
|
1348
|
+
// errors: 'a' does not exist in type '{ b: string; }'
|
|
1349
|
+
|
|
1350
|
+
type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>;
|
|
1351
|
+
//=> {a: number} & Partial<Record<'b', never>>
|
|
1352
|
+
|
|
1353
|
+
// @ts-expect-error
|
|
1354
|
+
const fooWithoutB: FooWithoutB = {a: 1, b: '2'};
|
|
1355
|
+
// errors at 'b': Type 'string' is not assignable to type 'undefined'.
|
|
1356
|
+
|
|
1357
|
+
// The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures.
|
|
1358
|
+
|
|
1359
|
+
// Consider the following example:
|
|
1360
|
+
|
|
1361
|
+
type UserData = {
|
|
1362
|
+
[metadata: string]: string;
|
|
1363
|
+
email: string;
|
|
1364
|
+
name: string;
|
|
1365
|
+
role: 'admin' | 'user';
|
|
1366
|
+
};
|
|
1367
|
+
|
|
1368
|
+
// `Omit` clearly doesn't behave as expected in this case:
|
|
1369
|
+
type PostPayload = Omit<UserData, 'email'>;
|
|
1370
|
+
//=> {[x: string]: string; [x: number]: string}
|
|
1371
|
+
|
|
1372
|
+
// In situations like this, `Except` works better.
|
|
1373
|
+
// It simply removes the `email` key while preserving all the other keys.
|
|
1374
|
+
type PostPayloadFixed = Except<UserData, 'email'>;
|
|
1375
|
+
//=> {[x: string]: string; name: string; role: 'admin' | 'user'}
|
|
1376
|
+
```
|
|
1377
|
+
|
|
1378
|
+
@category Object
|
|
1379
|
+
*/
|
|
1380
|
+
type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {}> =
|
|
1381
|
+
_Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>;
|
|
1382
|
+
|
|
1383
|
+
type _Except<ObjectType, KeysType extends keyof ObjectType, Options extends Required<ExceptOptions>> = {
|
|
1384
|
+
[KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
|
|
1385
|
+
} & (Options['requireExactProps'] extends true
|
|
1386
|
+
? Partial<Record<KeysType, never>>
|
|
1387
|
+
: {});
|
|
1388
|
+
|
|
1389
|
+
/**
|
|
1390
|
+
Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.
|
|
1391
|
+
|
|
1392
|
+
Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.
|
|
1393
|
+
|
|
1394
|
+
@example
|
|
1395
|
+
```
|
|
1396
|
+
import type {SetRequired} from 'type-fest';
|
|
1397
|
+
|
|
1398
|
+
type Foo = {
|
|
1399
|
+
a?: number;
|
|
1400
|
+
b: string;
|
|
1401
|
+
c?: boolean;
|
|
1402
|
+
};
|
|
1403
|
+
|
|
1404
|
+
type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
|
|
1405
|
+
// type SomeRequired = {
|
|
1406
|
+
// a?: number;
|
|
1407
|
+
// b: string; // Was already required and still is.
|
|
1408
|
+
// c: boolean; // Is now required.
|
|
1409
|
+
// }
|
|
1410
|
+
|
|
1411
|
+
// Set specific indices in an array to be required.
|
|
1412
|
+
type ArrayExample = SetRequired<[number?, number?, number?], 0 | 1>;
|
|
1413
|
+
//=> [number, number, number?]
|
|
1414
|
+
```
|
|
1415
|
+
|
|
1416
|
+
@category Object
|
|
1417
|
+
*/
|
|
1418
|
+
type SetRequired<BaseType, Keys extends keyof BaseType> =
|
|
1419
|
+
(BaseType extends (...arguments_: never) => any
|
|
1420
|
+
? (...arguments_: Parameters<BaseType>) => ReturnType<BaseType>
|
|
1421
|
+
: unknown)
|
|
1422
|
+
& _SetRequired<BaseType, Keys>;
|
|
1423
|
+
|
|
1424
|
+
type _SetRequired<BaseType, Keys extends keyof BaseType> =
|
|
1425
|
+
BaseType extends UnknownArray
|
|
1426
|
+
? SetArrayRequired<BaseType, Keys> extends infer ResultantArray
|
|
1427
|
+
? If<IsArrayReadonly<BaseType>, Readonly<ResultantArray>, ResultantArray>
|
|
1428
|
+
: never
|
|
1429
|
+
: Simplify<
|
|
1430
|
+
// Pick just the keys that are optional from the base type.
|
|
1431
|
+
Except<BaseType, Keys> &
|
|
1432
|
+
// Pick the keys that should be required from the base type and make them required.
|
|
1433
|
+
Required<HomomorphicPick<BaseType, Keys>>
|
|
1434
|
+
>;
|
|
1435
|
+
|
|
1436
|
+
/**
|
|
1437
|
+
Remove the optional modifier from the specified keys in an array.
|
|
1438
|
+
*/
|
|
1439
|
+
type SetArrayRequired<
|
|
1440
|
+
TArray extends UnknownArray,
|
|
1441
|
+
Keys,
|
|
1442
|
+
Counter extends any[] = [],
|
|
1443
|
+
Accumulator extends UnknownArray = [],
|
|
1444
|
+
> = TArray extends unknown // For distributing `TArray` when it's a union
|
|
1445
|
+
? keyof TArray & `${number}` extends never
|
|
1446
|
+
// Exit if `TArray` is empty (e.g., []), or
|
|
1447
|
+
// `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
|
|
1448
|
+
? [...Accumulator, ...TArray]
|
|
1449
|
+
: TArray extends readonly [(infer First)?, ...infer Rest]
|
|
1450
|
+
? '0' extends OptionalKeysOf<TArray> // If the first element of `TArray` is optional
|
|
1451
|
+
? `${Counter['length']}` extends `${Keys & (string | number)}` // If the current index needs to be required
|
|
1452
|
+
? SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, First]>
|
|
1453
|
+
// If the current element is optional, but it doesn't need to be required,
|
|
1454
|
+
// then we can exit early, since no further elements can now be made required.
|
|
1455
|
+
: [...Accumulator, ...TArray]
|
|
1456
|
+
: SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, TArray[0]]>
|
|
1457
|
+
: never // Should never happen, since `[(infer F)?, ...infer R]` is a top-type for arrays.
|
|
1458
|
+
: never; // Should never happen
|
|
1459
|
+
|
|
1460
|
+
type SetFieldTypeOptions = {
|
|
1461
|
+
/**
|
|
1462
|
+
Preserve optional and readonly modifiers for properties being updated.
|
|
1463
|
+
|
|
1464
|
+
NOTE: Property modifiers will always be preserved for properties that are not being updated.
|
|
1465
|
+
|
|
1466
|
+
@default true
|
|
1467
|
+
*/
|
|
1468
|
+
preservePropertyModifiers?: boolean;
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
type DefaultSetFieldTypeOptions = {
|
|
1472
|
+
preservePropertyModifiers: true;
|
|
1473
|
+
};
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
Create a type that changes the type of the given keys.
|
|
1477
|
+
|
|
1478
|
+
Use-cases:
|
|
1479
|
+
- Creating variations of a base model.
|
|
1480
|
+
- Fixing incorrect external types.
|
|
1481
|
+
|
|
1482
|
+
@see `Merge` if you need to change multiple properties to different types.
|
|
1483
|
+
|
|
1484
|
+
@example
|
|
1485
|
+
```
|
|
1486
|
+
import type {SetFieldType} from 'type-fest';
|
|
1487
|
+
|
|
1488
|
+
type MyModel = {
|
|
1489
|
+
readonly id: number;
|
|
1490
|
+
readonly createdAt: Date;
|
|
1491
|
+
updatedAt?: Date;
|
|
1492
|
+
};
|
|
1493
|
+
|
|
1494
|
+
type MyModelApi1 = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string>;
|
|
1495
|
+
// {
|
|
1496
|
+
// readonly id: number;
|
|
1497
|
+
// readonly createdAt: string;
|
|
1498
|
+
// updatedAt?: string;
|
|
1499
|
+
// }
|
|
1500
|
+
|
|
1501
|
+
// `preservePropertyModifiers` option can be set to `false` if you want to remove property modifiers for properties being updated
|
|
1502
|
+
type MyModelApi2 = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string, {preservePropertyModifiers: false}>;
|
|
1503
|
+
// {
|
|
1504
|
+
// readonly id: number;
|
|
1505
|
+
// createdAt: string; // no longer readonly
|
|
1506
|
+
// updatedAt: string; // no longer optional
|
|
1507
|
+
// }
|
|
1508
|
+
```
|
|
1509
|
+
|
|
1510
|
+
@category Object
|
|
1511
|
+
*/
|
|
1512
|
+
type SetFieldType<BaseType, Keys extends keyof BaseType, NewType, Options extends SetFieldTypeOptions = {}> =
|
|
1513
|
+
_SetFieldType<BaseType, Keys, NewType, ApplyDefaultOptions<SetFieldTypeOptions, DefaultSetFieldTypeOptions, Options>>;
|
|
1514
|
+
|
|
1515
|
+
type _SetFieldType<BaseType, Keys extends keyof BaseType, NewType, Options extends Required<SetFieldTypeOptions>> =
|
|
1516
|
+
Simplify<{
|
|
1517
|
+
[P in keyof BaseType]: P extends Keys ? NewType : BaseType[P];
|
|
1518
|
+
} & (
|
|
1519
|
+
// `Record` is used to remove property modifiers
|
|
1520
|
+
Options['preservePropertyModifiers'] extends false ? Record<Keys, NewType> : unknown
|
|
1521
|
+
)>;
|
|
1522
|
+
|
|
1523
|
+
/**
|
|
1524
|
+
Create a type with shared fields from a union of object types.
|
|
1525
|
+
|
|
1526
|
+
Use-cases:
|
|
1527
|
+
- You want a safe object type where each key exists in the union object.
|
|
1528
|
+
- You want to focus on the common fields of the union type and don't want to have to care about the other fields.
|
|
1529
|
+
|
|
1530
|
+
@example
|
|
1531
|
+
```
|
|
1532
|
+
import type {SharedUnionFields} from 'type-fest';
|
|
1533
|
+
|
|
1534
|
+
type Cat = {
|
|
1535
|
+
name: string;
|
|
1536
|
+
type: 'cat';
|
|
1537
|
+
catType: string;
|
|
1538
|
+
};
|
|
1539
|
+
|
|
1540
|
+
type Dog = {
|
|
1541
|
+
name: string;
|
|
1542
|
+
type: 'dog';
|
|
1543
|
+
dogType: string;
|
|
1544
|
+
};
|
|
1545
|
+
|
|
1546
|
+
function displayPetInfo(petInfo: Cat | Dog) {
|
|
1547
|
+
// typeof petInfo =>
|
|
1548
|
+
// {
|
|
1549
|
+
// name: string;
|
|
1550
|
+
// type: 'cat';
|
|
1551
|
+
// catType: string; // Needn't care about this field, because it's not a common pet info field.
|
|
1552
|
+
// } | {
|
|
1553
|
+
// name: string;
|
|
1554
|
+
// type: 'dog';
|
|
1555
|
+
// dogType: string; // Needn't care about this field, because it's not a common pet info field.
|
|
1556
|
+
// }
|
|
1557
|
+
|
|
1558
|
+
// petInfo type is complex and have some needless fields
|
|
1559
|
+
|
|
1560
|
+
console.log('name:', petInfo.name);
|
|
1561
|
+
console.log('type:', petInfo.type);
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
function displayPetInfoWithSharedUnionFields(petInfo: SharedUnionFields<Cat | Dog>) {
|
|
1565
|
+
// typeof petInfo =>
|
|
1566
|
+
// {
|
|
1567
|
+
// name: string;
|
|
1568
|
+
// type: 'cat' | 'dog';
|
|
1569
|
+
// }
|
|
1570
|
+
|
|
1571
|
+
// petInfo type is simple and clear
|
|
1572
|
+
|
|
1573
|
+
console.log('name:', petInfo.name);
|
|
1574
|
+
console.log('type:', petInfo.type);
|
|
1575
|
+
}
|
|
1576
|
+
```
|
|
1577
|
+
|
|
1578
|
+
@see {@link SharedUnionFieldsDeep}
|
|
1579
|
+
@see {@link AllUnionFields}
|
|
1580
|
+
|
|
1581
|
+
@category Object
|
|
1582
|
+
@category Union
|
|
1583
|
+
*/
|
|
1584
|
+
type SharedUnionFields<Union> =
|
|
1585
|
+
Extract<Union, NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | UnknownArray> extends infer SkippedMembers
|
|
1586
|
+
? Exclude<Union, SkippedMembers> extends infer RelevantMembers
|
|
1587
|
+
?
|
|
1588
|
+
| SkippedMembers
|
|
1589
|
+
| (IsNever<RelevantMembers> extends true
|
|
1590
|
+
? never
|
|
1591
|
+
: Simplify<Pick<RelevantMembers, keyof RelevantMembers>>)
|
|
1592
|
+
: never
|
|
1593
|
+
: never;
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
Create a type with all fields from a union of object types.
|
|
1597
|
+
|
|
1598
|
+
Use-cases:
|
|
1599
|
+
- You want a safe object type where each key exists in the union object.
|
|
1600
|
+
|
|
1601
|
+
@example
|
|
1602
|
+
```
|
|
1603
|
+
import type {AllUnionFields} from 'type-fest';
|
|
1604
|
+
|
|
1605
|
+
type Cat = {
|
|
1606
|
+
name: string;
|
|
1607
|
+
type: 'cat';
|
|
1608
|
+
catType: string;
|
|
1609
|
+
};
|
|
1610
|
+
|
|
1611
|
+
type Dog = {
|
|
1612
|
+
name: string;
|
|
1613
|
+
type: 'dog';
|
|
1614
|
+
dogType: string;
|
|
1615
|
+
};
|
|
1616
|
+
|
|
1617
|
+
function displayPetInfo(petInfo: Cat | Dog) {
|
|
1618
|
+
// typeof petInfo =>
|
|
1619
|
+
// {
|
|
1620
|
+
// name: string;
|
|
1621
|
+
// type: 'cat';
|
|
1622
|
+
// catType: string;
|
|
1623
|
+
// } | {
|
|
1624
|
+
// name: string;
|
|
1625
|
+
// type: 'dog';
|
|
1626
|
+
// dogType: string;
|
|
1627
|
+
// }
|
|
1628
|
+
|
|
1629
|
+
console.log('name:', petInfo.name);
|
|
1630
|
+
console.log('type:', petInfo.type);
|
|
1631
|
+
|
|
1632
|
+
// TypeScript complains about `catType` and `dogType` not existing on type `Cat | Dog`.
|
|
1633
|
+
// @ts-expect-error
|
|
1634
|
+
console.log('animal type:', petInfo.catType ?? petInfo.dogType);
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
function displayPetInfoWithAllUnionFields(petInfo: AllUnionFields<Cat | Dog>) {
|
|
1638
|
+
// typeof petInfo =>
|
|
1639
|
+
// {
|
|
1640
|
+
// name: string;
|
|
1641
|
+
// type: 'cat' | 'dog';
|
|
1642
|
+
// catType?: string;
|
|
1643
|
+
// dogType?: string;
|
|
1644
|
+
// }
|
|
1645
|
+
|
|
1646
|
+
console.log('name:', petInfo.name);
|
|
1647
|
+
console.log('type:', petInfo.type);
|
|
1648
|
+
|
|
1649
|
+
// No TypeScript error.
|
|
1650
|
+
console.log('animal type:', petInfo.catType ?? petInfo.dogType);
|
|
1651
|
+
}
|
|
1652
|
+
```
|
|
1653
|
+
|
|
1654
|
+
@see {@link SharedUnionFields}
|
|
1655
|
+
|
|
1656
|
+
@category Object
|
|
1657
|
+
@category Union
|
|
1658
|
+
*/
|
|
1659
|
+
type AllUnionFields<Union> =
|
|
1660
|
+
Extract<Union, NonRecursiveType | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | UnknownArray> extends infer SkippedMembers
|
|
1661
|
+
? Exclude<Union, SkippedMembers> extends infer RelevantMembers
|
|
1662
|
+
?
|
|
1663
|
+
| SkippedMembers
|
|
1664
|
+
| Simplify<
|
|
1665
|
+
// Include fields that are common in all union members
|
|
1666
|
+
SharedUnionFields<RelevantMembers> &
|
|
1667
|
+
// Include readonly fields present in any union member
|
|
1668
|
+
{
|
|
1669
|
+
readonly [P in ReadonlyKeysOfUnion<RelevantMembers>]?: ValueOfUnion<RelevantMembers, P & KeysOfUnion<RelevantMembers>>
|
|
1670
|
+
} &
|
|
1671
|
+
// Include remaining fields that are neither common nor readonly
|
|
1672
|
+
{
|
|
1673
|
+
[P in Exclude<KeysOfUnion<RelevantMembers>, ReadonlyKeysOfUnion<RelevantMembers> | keyof RelevantMembers>]?: ValueOfUnion<RelevantMembers, P>
|
|
1674
|
+
}
|
|
1675
|
+
>
|
|
1676
|
+
: never
|
|
1677
|
+
: never;
|
|
1678
|
+
|
|
1679
|
+
/**
|
|
1680
|
+
Returns a boolean for whether the given string literal is lowercase.
|
|
1681
|
+
|
|
1682
|
+
@example
|
|
1683
|
+
```
|
|
1684
|
+
import type {IsLowercase} from 'type-fest';
|
|
1685
|
+
|
|
1686
|
+
type A = IsLowercase<'abc'>;
|
|
1687
|
+
//=> true
|
|
1688
|
+
|
|
1689
|
+
type B = IsLowercase<'Abc'>;
|
|
1690
|
+
//=> false
|
|
1691
|
+
|
|
1692
|
+
type C = IsLowercase<string>;
|
|
1693
|
+
//=> boolean
|
|
1694
|
+
```
|
|
1695
|
+
*/
|
|
1696
|
+
type IsLowercase<S extends string> = AllExtend<_IsLowercase<S>, true>;
|
|
1697
|
+
|
|
1698
|
+
/**
|
|
1699
|
+
Loops through each part in the string and returns a boolean array indicating whether each part is lowercase.
|
|
1700
|
+
*/
|
|
1701
|
+
type _IsLowercase<S extends string, Accumulator extends boolean[] = []> = S extends `${infer First}${infer Rest}`
|
|
1702
|
+
? _IsLowercase<Rest, [...Accumulator, IsLowercaseHelper<First>]>
|
|
1703
|
+
: [...Accumulator, IsLowercaseHelper<S>];
|
|
1704
|
+
|
|
1705
|
+
/**
|
|
1706
|
+
Returns a boolean for whether an individual part of the string is lowercase.
|
|
1707
|
+
*/
|
|
1708
|
+
type IsLowercaseHelper<S extends string> = S extends Lowercase<string>
|
|
1709
|
+
? true
|
|
1710
|
+
: S extends Uppercase<string> | Capitalize<string> | `${string}${Uppercase<string>}${string}`
|
|
1711
|
+
? false
|
|
1712
|
+
: boolean;
|
|
1713
|
+
|
|
1714
|
+
/**
|
|
1715
|
+
Returns a boolean for whether the given string literal is uppercase.
|
|
1716
|
+
|
|
1717
|
+
@example
|
|
1718
|
+
```
|
|
1719
|
+
import type {IsUppercase} from 'type-fest';
|
|
1720
|
+
|
|
1721
|
+
type A = IsUppercase<'ABC'>;
|
|
1722
|
+
//=> true
|
|
1723
|
+
|
|
1724
|
+
type B = IsUppercase<'Abc'>;
|
|
1725
|
+
//=> false
|
|
1726
|
+
|
|
1727
|
+
type C = IsUppercase<string>;
|
|
1728
|
+
//=> boolean
|
|
1729
|
+
```
|
|
1730
|
+
*/
|
|
1731
|
+
type IsUppercase<S extends string> = AllExtend<_IsUppercase<S>, true>;
|
|
1732
|
+
|
|
1733
|
+
/**
|
|
1734
|
+
Loops through each part in the string and returns a boolean array indicating whether each part is uppercase.
|
|
1735
|
+
*/
|
|
1736
|
+
type _IsUppercase<S extends string, Accumulator extends boolean[] = []> = S extends `${infer First}${infer Rest}`
|
|
1737
|
+
? _IsUppercase<Rest, [...Accumulator, IsUppercaseHelper<First>]>
|
|
1738
|
+
: [...Accumulator, IsUppercaseHelper<S>];
|
|
1739
|
+
|
|
1740
|
+
/**
|
|
1741
|
+
Returns a boolean for whether an individual part of the string is uppercase.
|
|
1742
|
+
*/
|
|
1743
|
+
type IsUppercaseHelper<S extends string> = S extends Uppercase<string>
|
|
1744
|
+
? true
|
|
1745
|
+
: S extends Lowercase<string> | Uncapitalize<string> | `${string}${Lowercase<string>}${string}`
|
|
1746
|
+
? false
|
|
1747
|
+
: boolean;
|
|
1748
|
+
|
|
1749
|
+
type SkipEmptyWord<Word extends string> = Word extends '' ? [] : [Word];
|
|
1750
|
+
|
|
1751
|
+
type RemoveLastCharacter<
|
|
1752
|
+
Sentence extends string,
|
|
1753
|
+
Character extends string,
|
|
1754
|
+
> = Sentence extends `${infer LeftSide}${Character}`
|
|
1755
|
+
? SkipEmptyWord<LeftSide>
|
|
1756
|
+
: never;
|
|
1757
|
+
|
|
1758
|
+
/**
|
|
1759
|
+
Words options.
|
|
1760
|
+
|
|
1761
|
+
@see {@link Words}
|
|
1762
|
+
*/
|
|
1763
|
+
type WordsOptions = {
|
|
1764
|
+
/**
|
|
1765
|
+
Split on numeric sequence.
|
|
1766
|
+
|
|
1767
|
+
@default true
|
|
1768
|
+
|
|
1769
|
+
@example
|
|
1770
|
+
```
|
|
1771
|
+
import type {Words} from 'type-fest';
|
|
1772
|
+
|
|
1773
|
+
type Example1 = Words<'p2pNetwork', {splitOnNumbers: true}>;
|
|
1774
|
+
//=> ['p', '2', 'p', 'Network']
|
|
1775
|
+
|
|
1776
|
+
type Example2 = Words<'p2pNetwork', {splitOnNumbers: false}>;
|
|
1777
|
+
//=> ['p2p', 'Network']
|
|
1778
|
+
```
|
|
1779
|
+
*/
|
|
1780
|
+
splitOnNumbers?: boolean;
|
|
1781
|
+
};
|
|
1782
|
+
|
|
1783
|
+
type _DefaultWordsOptions = {
|
|
1784
|
+
splitOnNumbers: true;
|
|
1785
|
+
};
|
|
1786
|
+
|
|
1787
|
+
/**
|
|
1788
|
+
Split a string (almost) like Lodash's `_.words()` function.
|
|
1789
|
+
|
|
1790
|
+
- Split on each word that begins with a capital letter.
|
|
1791
|
+
- Split on each {@link WordSeparators}.
|
|
1792
|
+
- Split on numeric sequence.
|
|
1793
|
+
|
|
1794
|
+
@example
|
|
1795
|
+
```
|
|
1796
|
+
import type {Words} from 'type-fest';
|
|
1797
|
+
|
|
1798
|
+
type Words0 = Words<'helloWorld'>;
|
|
1799
|
+
//=> ['hello', 'World']
|
|
1800
|
+
|
|
1801
|
+
type Words1 = Words<'helloWORLD'>;
|
|
1802
|
+
//=> ['hello', 'WORLD']
|
|
1803
|
+
|
|
1804
|
+
type Words2 = Words<'hello-world'>;
|
|
1805
|
+
//=> ['hello', 'world']
|
|
1806
|
+
|
|
1807
|
+
type Words3 = Words<'--hello the_world'>;
|
|
1808
|
+
//=> ['hello', 'the', 'world']
|
|
1809
|
+
|
|
1810
|
+
type Words4 = Words<'lifeIs42'>;
|
|
1811
|
+
//=> ['life', 'Is', '42']
|
|
1812
|
+
|
|
1813
|
+
type Words5 = Words<'p2pNetwork', {splitOnNumbers: false}>;
|
|
1814
|
+
//=> ['p2p', 'Network']
|
|
1815
|
+
```
|
|
1816
|
+
|
|
1817
|
+
@category Change case
|
|
1818
|
+
@category Template literal
|
|
1819
|
+
*/
|
|
1820
|
+
type Words<Sentence extends string, Options extends WordsOptions = {}> =
|
|
1821
|
+
WordsImplementation<Sentence, ApplyDefaultOptions<WordsOptions, _DefaultWordsOptions, Options>>;
|
|
1822
|
+
|
|
1823
|
+
type WordsImplementation<
|
|
1824
|
+
Sentence extends string,
|
|
1825
|
+
Options extends Required<WordsOptions>,
|
|
1826
|
+
LastCharacter extends string = '',
|
|
1827
|
+
CurrentWord extends string = '',
|
|
1828
|
+
> = Sentence extends `${infer FirstCharacter}${infer RemainingCharacters}`
|
|
1829
|
+
? FirstCharacter extends WordSeparators
|
|
1830
|
+
// Skip word separator
|
|
1831
|
+
? [...SkipEmptyWord<CurrentWord>, ...WordsImplementation<RemainingCharacters, Options>]
|
|
1832
|
+
: LastCharacter extends ''
|
|
1833
|
+
// Fist char of word
|
|
1834
|
+
? WordsImplementation<RemainingCharacters, Options, FirstCharacter, FirstCharacter>
|
|
1835
|
+
// Case change: non-numeric to numeric
|
|
1836
|
+
: [false, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
|
|
1837
|
+
? Options['splitOnNumbers'] extends true
|
|
1838
|
+
// Split on number: push word
|
|
1839
|
+
? [...SkipEmptyWord<CurrentWord>, ...WordsImplementation<RemainingCharacters, Options, FirstCharacter, FirstCharacter>]
|
|
1840
|
+
// No split on number: concat word
|
|
1841
|
+
: WordsImplementation<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
|
|
1842
|
+
// Case change: numeric to non-numeric
|
|
1843
|
+
: [true, false] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
|
|
1844
|
+
? Options['splitOnNumbers'] extends true
|
|
1845
|
+
// Split on number: push word
|
|
1846
|
+
? [...SkipEmptyWord<CurrentWord>, ...WordsImplementation<RemainingCharacters, Options, FirstCharacter, FirstCharacter>]
|
|
1847
|
+
// No split on number: concat word
|
|
1848
|
+
: WordsImplementation<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
|
|
1849
|
+
// No case change: concat word
|
|
1850
|
+
: [true, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
|
|
1851
|
+
? WordsImplementation<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
|
|
1852
|
+
// Case change: lower to upper, push word
|
|
1853
|
+
: [true, true] extends [IsLowercase<LastCharacter>, IsUppercase<FirstCharacter>]
|
|
1854
|
+
? [...SkipEmptyWord<CurrentWord>, ...WordsImplementation<RemainingCharacters, Options, FirstCharacter, FirstCharacter>]
|
|
1855
|
+
// Case change: upper to lower, brings back the last character, push word
|
|
1856
|
+
: [true, true] extends [IsUppercase<LastCharacter>, IsLowercase<FirstCharacter>]
|
|
1857
|
+
? [...RemoveLastCharacter<CurrentWord, LastCharacter>, ...WordsImplementation<RemainingCharacters, Options, FirstCharacter, `${LastCharacter}${FirstCharacter}`>]
|
|
1858
|
+
// No case change: concat word
|
|
1859
|
+
: WordsImplementation<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
|
|
1860
|
+
: [...SkipEmptyWord<CurrentWord>];
|
|
1861
|
+
|
|
1862
|
+
/**
|
|
1863
|
+
CamelCase options.
|
|
1864
|
+
|
|
1865
|
+
@see {@link CamelCase}
|
|
1866
|
+
*/
|
|
1867
|
+
type CamelCaseOptions = WordsOptions & {
|
|
1868
|
+
/**
|
|
1869
|
+
Whether to preserved consecutive uppercase letter.
|
|
1870
|
+
|
|
1871
|
+
@default false
|
|
1872
|
+
*/
|
|
1873
|
+
preserveConsecutiveUppercase?: boolean;
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
type _DefaultCamelCaseOptions = {
|
|
1877
|
+
splitOnNumbers: true;
|
|
1878
|
+
preserveConsecutiveUppercase: false;
|
|
1879
|
+
};
|
|
1880
|
+
|
|
1881
|
+
/**
|
|
1882
|
+
Convert an array of words to camel-case.
|
|
1883
|
+
*/
|
|
1884
|
+
type CamelCaseFromArray<
|
|
1885
|
+
Words extends string[],
|
|
1886
|
+
Options extends Required<CamelCaseOptions>,
|
|
1887
|
+
OutputString extends string = '',
|
|
1888
|
+
> = Words extends [
|
|
1889
|
+
infer FirstWord extends string,
|
|
1890
|
+
...infer RemainingWords extends string[],
|
|
1891
|
+
]
|
|
1892
|
+
? Options['preserveConsecutiveUppercase'] extends true
|
|
1893
|
+
? `${Capitalize<FirstWord>}${CamelCaseFromArray<RemainingWords, Options>}`
|
|
1894
|
+
: `${Capitalize<Lowercase<FirstWord>>}${CamelCaseFromArray<RemainingWords, Options>}`
|
|
1895
|
+
: OutputString;
|
|
1896
|
+
|
|
1897
|
+
/**
|
|
1898
|
+
Convert a string literal to camel-case.
|
|
1899
|
+
|
|
1900
|
+
This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
|
|
1901
|
+
|
|
1902
|
+
By default, consecutive uppercase letter are preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour.
|
|
1903
|
+
|
|
1904
|
+
@example
|
|
1905
|
+
```
|
|
1906
|
+
import type {CamelCase} from 'type-fest';
|
|
1907
|
+
|
|
1908
|
+
// Simple
|
|
1909
|
+
|
|
1910
|
+
const someVariable: CamelCase<'foo-bar'> = 'fooBar';
|
|
1911
|
+
const preserveConsecutiveUppercase: CamelCase<'foo-BAR-baz', {preserveConsecutiveUppercase: true}> = 'fooBARBaz';
|
|
1912
|
+
|
|
1913
|
+
// Advanced
|
|
1914
|
+
|
|
1915
|
+
type CamelCasedProperties<T> = {
|
|
1916
|
+
[K in keyof T as CamelCase<K>]: T[K]
|
|
1917
|
+
};
|
|
1918
|
+
|
|
1919
|
+
type RawOptions = {
|
|
1920
|
+
'dry-run': boolean;
|
|
1921
|
+
'full_family_name': string;
|
|
1922
|
+
foo: number;
|
|
1923
|
+
BAR: string;
|
|
1924
|
+
QUZ_QUX: number;
|
|
1925
|
+
'OTHER-FIELD': boolean;
|
|
1926
|
+
};
|
|
1927
|
+
|
|
1928
|
+
const dbResult: CamelCasedProperties<RawOptions> = {
|
|
1929
|
+
dryRun: true,
|
|
1930
|
+
fullFamilyName: 'bar.js',
|
|
1931
|
+
foo: 123,
|
|
1932
|
+
bar: 'foo',
|
|
1933
|
+
quzQux: 6,
|
|
1934
|
+
otherField: false,
|
|
1935
|
+
};
|
|
1936
|
+
```
|
|
1937
|
+
|
|
1938
|
+
@category Change case
|
|
1939
|
+
@category Template literal
|
|
1940
|
+
*/
|
|
1941
|
+
type CamelCase<Type, Options extends CamelCaseOptions = {}> = Type extends string
|
|
1942
|
+
? string extends Type
|
|
1943
|
+
? Type
|
|
1944
|
+
: Uncapitalize<CamelCaseFromArray<
|
|
1945
|
+
Words<Type extends Uppercase<Type> ? Lowercase<Type> : Type, Options>,
|
|
1946
|
+
ApplyDefaultOptions<CamelCaseOptions, _DefaultCamelCaseOptions, Options>
|
|
1947
|
+
>>
|
|
1948
|
+
: Type;
|
|
1949
|
+
|
|
1950
|
+
/**
|
|
1951
|
+
* This is a fork of the Help class from the 'commander' npm package. The Help class method names as well as the
|
|
1952
|
+
* expected interface of the Command instance to parse, are both similar, but different and not compatible without
|
|
1953
|
+
* custom adaptations, @see ICommand
|
|
1954
|
+
*/
|
|
1955
|
+
declare class Help implements IHelp {
|
|
1956
|
+
protected readonly cmd: ICommand;
|
|
1957
|
+
/** output helpWidth, long lines are wrapped to fit */
|
|
1958
|
+
helpWidth: number;
|
|
1959
|
+
minWidthToWrap: number;
|
|
1960
|
+
sortSubcommands: boolean;
|
|
1961
|
+
sortOptions: boolean;
|
|
1962
|
+
usageDisplayOptionsAs: string;
|
|
1963
|
+
usageDisplaySubcommandAs: string;
|
|
1964
|
+
constructor(cmd: ICommand);
|
|
1965
|
+
/**
|
|
1966
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
1967
|
+
*/
|
|
1968
|
+
visibleCommands(): ICommand[];
|
|
1969
|
+
/**
|
|
1970
|
+
* Compare options for sort.
|
|
1971
|
+
*/
|
|
1972
|
+
compareOptions(a: Option, b: Option): number;
|
|
1973
|
+
/**
|
|
1974
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
1975
|
+
*/
|
|
1976
|
+
visibleOptions(): Option[];
|
|
1977
|
+
/**
|
|
1978
|
+
* Get an array of the arguments if any have a description.
|
|
1979
|
+
*/
|
|
1980
|
+
visibleArguments(): Argument[];
|
|
1981
|
+
/**
|
|
1982
|
+
* Get the command term to show in the list of subcommands.
|
|
1983
|
+
*/
|
|
1984
|
+
subcommandTerm(sub: ICommand): string;
|
|
1985
|
+
/**
|
|
1986
|
+
* Get the option term to show in the list of options.
|
|
1987
|
+
*/
|
|
1988
|
+
optionTerm(option: Option): string;
|
|
1989
|
+
/**
|
|
1990
|
+
* Get the argument term to show in the list of arguments.
|
|
1991
|
+
*/
|
|
1992
|
+
argumentTerm(argument: Argument): string;
|
|
1993
|
+
/**
|
|
1994
|
+
* Get the longest subcommand primary alias length.
|
|
1995
|
+
*/
|
|
1996
|
+
longestSubcommandAliasLength(): number;
|
|
1997
|
+
/**
|
|
1998
|
+
* Get the longest subcommand term length.
|
|
1999
|
+
*/
|
|
2000
|
+
longestSubcommandTermLength(): number;
|
|
2001
|
+
/**
|
|
2002
|
+
* Get the longest option term length.
|
|
2003
|
+
*/
|
|
2004
|
+
longestOptionTermLength(): number;
|
|
2005
|
+
/**
|
|
2006
|
+
* Get the longest argument term length.
|
|
2007
|
+
*/
|
|
2008
|
+
longestArgumentTermLength(): number;
|
|
2009
|
+
/**
|
|
2010
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
2011
|
+
*/
|
|
2012
|
+
commandUsage(): string;
|
|
2013
|
+
/**
|
|
2014
|
+
* Get the description for the command.
|
|
2015
|
+
*/
|
|
2016
|
+
commandDescription(): string;
|
|
2017
|
+
/**
|
|
2018
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
2019
|
+
* (Fallback to description for backwards compatibility.)
|
|
2020
|
+
*/
|
|
2021
|
+
subcommandDescription(sub: ICommand): string;
|
|
2022
|
+
/**
|
|
2023
|
+
* Get the option description to show in the list of options.
|
|
2024
|
+
*/
|
|
2025
|
+
optionDescription(option: Option): string;
|
|
2026
|
+
/**
|
|
2027
|
+
* Get the argument description to show in the list of arguments.
|
|
2028
|
+
*/
|
|
2029
|
+
argumentDescription(argument: Argument): string;
|
|
2030
|
+
/**
|
|
2031
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
2032
|
+
*/
|
|
2033
|
+
formatItemList(heading: string, items: string[]): string[];
|
|
2034
|
+
/**
|
|
2035
|
+
* Group items by their help group heading.
|
|
2036
|
+
*/
|
|
2037
|
+
groupItems<T extends ICommand | Option>(unsortedItems: T[], visibleItems: T[], getGroup: (item: T) => string): Map<string, T[]>;
|
|
2038
|
+
/**
|
|
2039
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
2040
|
+
*/
|
|
2041
|
+
displayWidth(str: string): number;
|
|
2042
|
+
/**
|
|
2043
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
2044
|
+
*/
|
|
2045
|
+
styleTitle(str: string): string;
|
|
2046
|
+
/**
|
|
2047
|
+
* Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
|
|
2048
|
+
*/
|
|
2049
|
+
styleUsage(str: string): string;
|
|
2050
|
+
/**
|
|
2051
|
+
* Style command descriptions for display in help output.
|
|
2052
|
+
*/
|
|
2053
|
+
styleCommandDescription(str: string): string;
|
|
2054
|
+
/**
|
|
2055
|
+
* Style option descriptions for display in help output.
|
|
2056
|
+
*/
|
|
2057
|
+
styleOptionDescription(str: string): string;
|
|
2058
|
+
/**
|
|
2059
|
+
* Style subcommand descriptions for display in help output.
|
|
2060
|
+
*/
|
|
2061
|
+
styleSubcommandDescription(str: string): string;
|
|
2062
|
+
/**
|
|
2063
|
+
* Style argument descriptions for display in help output.
|
|
2064
|
+
*/
|
|
2065
|
+
styleArgumentDescription(str: string): string;
|
|
2066
|
+
/**
|
|
2067
|
+
* Base style used by descriptions. Override in subclass to apply custom formatting.
|
|
2068
|
+
*/
|
|
2069
|
+
styleDescriptionText(str: string): string;
|
|
2070
|
+
/**
|
|
2071
|
+
* Style option terms (flags) for display in help output.
|
|
2072
|
+
*/
|
|
2073
|
+
styleOptionTerm(str: string): string;
|
|
2074
|
+
/**
|
|
2075
|
+
* Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
|
|
2076
|
+
*/
|
|
2077
|
+
styleSubcommandTerm(str: string): string;
|
|
2078
|
+
/**
|
|
2079
|
+
* Style argument terms for display in help output.
|
|
2080
|
+
*/
|
|
2081
|
+
styleArgumentTerm(str: string): string;
|
|
2082
|
+
/**
|
|
2083
|
+
* Base style used in terms and usage for options. Override in subclass to apply custom formatting.
|
|
2084
|
+
*/
|
|
2085
|
+
styleOptionText(str: string): string;
|
|
2086
|
+
/**
|
|
2087
|
+
* Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
|
|
2088
|
+
*/
|
|
2089
|
+
styleArgumentText(str: string): string;
|
|
2090
|
+
/**
|
|
2091
|
+
* Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
|
|
2092
|
+
*/
|
|
2093
|
+
styleSubcommandText(str: string): string;
|
|
2094
|
+
/**
|
|
2095
|
+
* Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
|
|
2096
|
+
*/
|
|
2097
|
+
styleCommandText(str: string): string;
|
|
2098
|
+
/**
|
|
2099
|
+
* Calculate the pad width from the maximum term length.
|
|
2100
|
+
*/
|
|
2101
|
+
padWidth(): number;
|
|
2102
|
+
/**
|
|
2103
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
2104
|
+
*/
|
|
2105
|
+
preformatted(str: string): boolean;
|
|
2106
|
+
/**
|
|
2107
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
2108
|
+
*
|
|
2109
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
2110
|
+
* TTT DDD DDDD
|
|
2111
|
+
* DD DDD
|
|
2112
|
+
*/
|
|
2113
|
+
formatItem(term: string, termWidth: number, description: string): string;
|
|
2114
|
+
/**
|
|
2115
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
2116
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
2117
|
+
*/
|
|
2118
|
+
boxWrap(str: string, width: number): string;
|
|
2119
|
+
/**
|
|
2120
|
+
* Generate the built-in help text.
|
|
2121
|
+
*/
|
|
2122
|
+
render(): string;
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
/**
|
|
2126
|
+
* a type-safe CLI composer that can parse argv and generate help without execution coupling.
|
|
2127
|
+
*/
|
|
2128
|
+
declare class Command<A extends Arguments = [], O extends Options = {
|
|
2129
|
+
help?: boolean;
|
|
2130
|
+
debug?: boolean;
|
|
2131
|
+
}, Subs extends SubCommands = SubCommands> implements ICommand {
|
|
2132
|
+
/** parent command in the hierarchy, undefined for root command */
|
|
2133
|
+
parent?: Command<Arguments, Options & O>;
|
|
2134
|
+
/** the command name used to invoke it */
|
|
2135
|
+
name: string;
|
|
2136
|
+
/** semantic version string displayed by --version flag */
|
|
2137
|
+
version?: string;
|
|
2138
|
+
/** alternative names for invoking this command */
|
|
2139
|
+
aliases: string[];
|
|
2140
|
+
/** brief one-line description shown in command lists */
|
|
2141
|
+
summary?: string;
|
|
2142
|
+
/** full description displayed in help text */
|
|
2143
|
+
description: string;
|
|
2144
|
+
/** whether to exclude from help listings */
|
|
2145
|
+
hidden?: boolean;
|
|
2146
|
+
/** category for organizing related commands in help output */
|
|
2147
|
+
group?: string;
|
|
2148
|
+
/** positional arguments this command accepts */
|
|
2149
|
+
arguments: Argument[];
|
|
2150
|
+
/** cLI options (flags) this command recognizes */
|
|
2151
|
+
options: Option[];
|
|
2152
|
+
/** subcommands registered with this command */
|
|
2153
|
+
commands: Subs;
|
|
2154
|
+
/** main action handler executed when command is invoked */
|
|
2155
|
+
protected action?: ActionHandler<A, O, Subs>;
|
|
2156
|
+
/** option-driven actions (e.g., --help, --version) executed when their conditions match */
|
|
2157
|
+
protected hooks: HookDefinition<Arguments, Options & O>[];
|
|
2158
|
+
constructor(name: string, parent?: ICommand);
|
|
2159
|
+
protected get help(): Help;
|
|
2160
|
+
/** configure how the help is rendered */
|
|
2161
|
+
helpConfiguration(cb?: (help: Help) => void): this;
|
|
2162
|
+
/** renders formatted help text using provided help definition */
|
|
2163
|
+
renderHelp(config?: {
|
|
2164
|
+
noColor?: boolean;
|
|
2165
|
+
}): string;
|
|
2166
|
+
/** sets the command name */
|
|
2167
|
+
setName(name: string): void;
|
|
2168
|
+
/** sets command aliases, flattening nested arrays */
|
|
2169
|
+
setAliases(...aliases: (string | string[])[]): this;
|
|
2170
|
+
/** adds aliases to existing ones */
|
|
2171
|
+
addAliases(...aliases: (string | string[])[]): this;
|
|
2172
|
+
/** sets the command version */
|
|
2173
|
+
setVersion(version: string): InferAddOptionResult<A, O, {
|
|
2174
|
+
version?: boolean;
|
|
2175
|
+
}, Subs>;
|
|
2176
|
+
/** sets the command summary */
|
|
2177
|
+
setSummary(summary?: string): this;
|
|
2178
|
+
/** sets command description, joining variadic lines */
|
|
2179
|
+
setDescription(...lines: string[]): this;
|
|
2180
|
+
/** sets whether command is hidden from help */
|
|
2181
|
+
setHidden(hidden?: boolean | undefined): this;
|
|
2182
|
+
/** sets the command group for help organization */
|
|
2183
|
+
setGroup(group?: string): this;
|
|
2184
|
+
/** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
|
|
2185
|
+
command<Name extends string, Sub extends Command<any, any, any> = Command<[], O, {}>>(name: Name, cb?: (cmd: Command<[], O, {}>, parent: this) => Sub): Sub;
|
|
2186
|
+
/** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
|
|
2187
|
+
addCommand<Name extends string, Sub extends Command<any, any, any> = Command<[], O, {}>>(name: Name, cb: (cmd: Command<[], O, {}>, parent: this) => Sub): Command<A, O, (SubCommands extends Subs ? {} : Subs) & {
|
|
2188
|
+
[K in Name]: Sub;
|
|
2189
|
+
}>;
|
|
2190
|
+
/** add required variadic argument, eg.: `<name...>` */
|
|
2191
|
+
addArgument<const Opts extends RequiredVariadicArgumentOptions>(usage: AllowedArgumentUsage<this, `<${string}...>`>, options?: Opts): Command<[...A, InferAddedArgumentType<Opts>[]], O, Subs>;
|
|
2192
|
+
/** add required argument, eg.: `<name>` */
|
|
2193
|
+
addArgument<const Opts extends RequiredArgumentOptions>(usage: AllowedArgumentUsage<this, `<${string}>`>, options?: Opts): Command<[...A, InferAddedArgumentType<Opts>], O, Subs>;
|
|
2194
|
+
/** add optional variadic argument with defaults, eg.: `[name...]` */
|
|
2195
|
+
addArgument<const Opts extends OptionalVariadicArgumentOptions>(usage: AllowedArgumentUsage<this, `[${string}...]`>, options?: Opts): Command<[...A, InferAddedArgumentType<Opts>[]], O, Subs>;
|
|
2196
|
+
/** add optional argument with default, eg.: `[name]` */
|
|
2197
|
+
addArgument<const Opts extends OptionalArgumentOptionsWithDefaultValue>(usage: AllowedArgumentUsage<this, `[${string}]`>, options: Opts): Command<[...A, InferAddedArgumentType<Opts>], O, Subs>;
|
|
2198
|
+
/** add optional argument, eg.: `[name]` */
|
|
2199
|
+
addArgument<const Opts extends OptionalArgumentOptions>(usage: AllowedArgumentUsage<this, `[${string}]`>, options?: Opts): Command<[...A, InferAddedArgumentType<Opts> | undefined], O, Subs>;
|
|
2200
|
+
/** add optional string option, eg.: `-o, --output [path]` */
|
|
2201
|
+
addOption<Long extends string>(flags: `-${string}, --${Long} [${string}]`, options?: SetFieldType<OptionalOptionOptions, 'defaultValue', undefined | never>): Command<A, Simplify<{
|
|
2202
|
+
[K in CamelCase<Long>]?: string;
|
|
2203
|
+
} & O>, Subs>;
|
|
2204
|
+
/** add optional string option with default, eg.: `-o, --output [path]` */
|
|
2205
|
+
addOption<Long extends string>(flags: `-${string}, --${Long} [${string}]`, options: SetFieldType<SetRequired<OptionalOptionOptions, 'defaultValue'>, 'defaultValue', string>): Command<A, Simplify<{
|
|
2206
|
+
[K in CamelCase<Long>]: string;
|
|
2207
|
+
} & O>, Subs>;
|
|
2208
|
+
/** add required variadic option, eg.: `-i, --include <patterns...>` */
|
|
2209
|
+
addOption<Long extends string>(flags: `-${string}, --${Long} <${string}...>`, options?: RequiredVariadicOptionOptions): Command<A, Simplify<{
|
|
2210
|
+
[K in CamelCase<Long>]: string[];
|
|
2211
|
+
} & O>, Subs>;
|
|
2212
|
+
/** add optional variadic option with defaults, eg.: `-e, --exclude [patterns...]` */
|
|
2213
|
+
addOption<Long extends string>(flags: `-${string}, --${Long} [${string}...]`, options?: OptionalVariadicOptionOptions): Command<A, Simplify<{
|
|
2214
|
+
[K in CamelCase<Long>]: string[];
|
|
2215
|
+
} & O>, Subs>;
|
|
2216
|
+
/** add required string option, eg.: `-f, --file <path>` */
|
|
2217
|
+
addOption<Long extends string>(flags: `-${string}, --${Long} <${string}>`, options?: RequiredOptionOptions): Command<A, Simplify<{
|
|
2218
|
+
[K in CamelCase<Long>]: string;
|
|
2219
|
+
} & O>, Subs>;
|
|
2220
|
+
/** add boolean flag option with default, eg.: `-v, --verbose` */
|
|
2221
|
+
addOption<Long extends string>(flags: `-${string}, --${Long}`, options: SetFieldType<SetRequired<BooleanOptionOptions, 'defaultValue'>, 'defaultValue', boolean>): Command<A, Simplify<{
|
|
2222
|
+
[K in CamelCase<Long>]: boolean;
|
|
2223
|
+
} & O>, Subs>;
|
|
2224
|
+
/** add boolean flag option, eg.: `-v, --verbose` */
|
|
2225
|
+
addOption<Long extends string>(flags: `-${string}, --${Long}`, options?: SetFieldType<BooleanOptionOptions, 'defaultValue', undefined | never>): Command<A, Simplify<{
|
|
2226
|
+
[K in CamelCase<Long>]?: boolean;
|
|
2227
|
+
} & O>, Subs>;
|
|
2228
|
+
/**
|
|
2229
|
+
* register an action to be invoked when an option is set to true or string value.
|
|
2230
|
+
*
|
|
2231
|
+
* Hooks execute in addition to or instead of the main action handler,
|
|
2232
|
+
* allowing for option-driven behavior. For example, `--help` and `--version`
|
|
2233
|
+
* are implemented as hooks.
|
|
2234
|
+
*/
|
|
2235
|
+
addOptionHook(optionName: keyof O, action: HookActionHandler<Arguments, O>): this;
|
|
2236
|
+
/** parses command-line arguments with subcommand support and type-safe validation. */
|
|
2237
|
+
parseArgv(argv?: string[]): ParseArgvResult<Arguments, Options & O>;
|
|
2238
|
+
/**
|
|
2239
|
+
* sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
|
|
2240
|
+
* The handler receives parsed arguments and options with correct typings.
|
|
2241
|
+
*/
|
|
2242
|
+
setAction(fn: ActionHandler<A, O, Subs>): this;
|
|
2243
|
+
/** returns a new Command instance. Override this method in subclasses. */
|
|
2244
|
+
protected createSubcommand(name: string): Command<[], O, {}>;
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
/** Logger interface defining methods for different log levels. */
|
|
2248
|
+
interface Logger {
|
|
2249
|
+
start: (...args: unknown[]) => void;
|
|
2250
|
+
done: (...args: unknown[]) => void;
|
|
2251
|
+
info: (...args: unknown[]) => void;
|
|
2252
|
+
log: (...args: unknown[]) => void;
|
|
2253
|
+
warn: (...args: unknown[]) => void;
|
|
2254
|
+
error: (...args: unknown[]) => void;
|
|
2255
|
+
debug: (...args: unknown[]) => void;
|
|
2256
|
+
}
|
|
2257
|
+
/** Parsed command-line arguments */
|
|
2258
|
+
type Arguments = (undefined | string | string[])[];
|
|
2259
|
+
/** Parsed command-line options */
|
|
2260
|
+
type Options = Record<string, undefined | boolean | string | string[]>;
|
|
2261
|
+
/** Result of parsing command-line input, including arguments, options, triggered actions, and execution method */
|
|
2262
|
+
type SubCommands = {
|
|
2263
|
+
[name: string]: Command<Arguments, Options, any>;
|
|
2264
|
+
};
|
|
2265
|
+
/** Base descriptor for command-line arguments with shared properties */
|
|
2266
|
+
interface Argument {
|
|
2267
|
+
usage: string;
|
|
2268
|
+
name: string;
|
|
2269
|
+
description?: string;
|
|
2270
|
+
required?: boolean;
|
|
2271
|
+
variadic?: boolean;
|
|
2272
|
+
choices?: string[];
|
|
2273
|
+
defaultValue?: string | string[];
|
|
2274
|
+
defaultValueDescription?: string;
|
|
2275
|
+
}
|
|
2276
|
+
/** Base descriptor for command-line options with shared properties */
|
|
2277
|
+
interface Option {
|
|
2278
|
+
type: 'boolean' | 'string';
|
|
2279
|
+
flags: string;
|
|
2280
|
+
short: string;
|
|
2281
|
+
long: string;
|
|
2282
|
+
name: string;
|
|
2283
|
+
argName?: string;
|
|
2284
|
+
description?: string;
|
|
2285
|
+
required?: boolean;
|
|
2286
|
+
variadic?: boolean;
|
|
2287
|
+
negate?: boolean;
|
|
2288
|
+
defaultValue?: boolean | string | string[];
|
|
2289
|
+
defaultValueDescription?: string;
|
|
2290
|
+
env?: string;
|
|
2291
|
+
hidden?: boolean;
|
|
2292
|
+
choices?: string[];
|
|
2293
|
+
group?: string;
|
|
2294
|
+
}
|
|
2295
|
+
/** Complete command configuration including all properties and substructures */
|
|
2296
|
+
interface ICommand {
|
|
2297
|
+
/** Parent command if this is a subcommand */
|
|
2298
|
+
readonly parent?: ICommand;
|
|
2299
|
+
/** Help configuration and rendering */
|
|
2300
|
+
/** Command name used for invocation */
|
|
2301
|
+
name: string;
|
|
2302
|
+
/** Alternative names for this command */
|
|
2303
|
+
aliases: string[];
|
|
2304
|
+
/** Optional version string */
|
|
2305
|
+
version?: string;
|
|
2306
|
+
/** Full command description */
|
|
2307
|
+
description: string;
|
|
2308
|
+
/** Brief single-line description */
|
|
2309
|
+
summary?: string;
|
|
2310
|
+
/** Whether command should be hidden from help */
|
|
2311
|
+
hidden?: boolean;
|
|
2312
|
+
/** Group name for organizing commands in help */
|
|
2313
|
+
group?: string;
|
|
2314
|
+
/** Positional arguments */
|
|
2315
|
+
arguments: Argument[];
|
|
2316
|
+
/** Named options/flags */
|
|
2317
|
+
options: Option[];
|
|
2318
|
+
/** Child subcommands */
|
|
2319
|
+
commands: {
|
|
2320
|
+
[name: string]: ICommand;
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
interface IHelp {
|
|
2324
|
+
/** output helpWidth, long lines are wrapped to fit */
|
|
2325
|
+
helpWidth: number;
|
|
2326
|
+
minWidthToWrap: number;
|
|
2327
|
+
sortSubcommands: boolean;
|
|
2328
|
+
sortOptions: boolean;
|
|
2329
|
+
usageDisplayOptionsAs: string;
|
|
2330
|
+
usageDisplaySubcommandAs: string;
|
|
2331
|
+
/**
|
|
2332
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
2333
|
+
*/
|
|
2334
|
+
visibleCommands(): ICommand[];
|
|
2335
|
+
/**
|
|
2336
|
+
* Compare options for sort.
|
|
2337
|
+
*/
|
|
2338
|
+
compareOptions(a: Option, b: Option): number;
|
|
2339
|
+
/**
|
|
2340
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
2341
|
+
*/
|
|
2342
|
+
visibleOptions(): Option[];
|
|
2343
|
+
/**
|
|
2344
|
+
* Get an array of the arguments if any have a description.
|
|
2345
|
+
*/
|
|
2346
|
+
visibleArguments(): Argument[];
|
|
2347
|
+
/**
|
|
2348
|
+
* Get the command term to show in the list of subcommands.
|
|
2349
|
+
*/
|
|
2350
|
+
subcommandTerm(sub: ICommand): string;
|
|
2351
|
+
/**
|
|
2352
|
+
* Get the option term to show in the list of options.
|
|
2353
|
+
*/
|
|
2354
|
+
optionTerm(option: Option): string;
|
|
2355
|
+
/**
|
|
2356
|
+
* Get the argument term to show in the list of arguments.
|
|
2357
|
+
*/
|
|
2358
|
+
argumentTerm(argument: Argument): string;
|
|
2359
|
+
/**
|
|
2360
|
+
* Get the longest subcommand primary alias length.
|
|
2361
|
+
*/
|
|
2362
|
+
longestSubcommandAliasLength(): number;
|
|
2363
|
+
/**
|
|
2364
|
+
* Get the longest subcommand term length.
|
|
2365
|
+
*/
|
|
2366
|
+
longestSubcommandTermLength(): number;
|
|
2367
|
+
/**
|
|
2368
|
+
* Get the longest option term length.
|
|
2369
|
+
*/
|
|
2370
|
+
longestOptionTermLength(): number;
|
|
2371
|
+
/**
|
|
2372
|
+
* Get the longest argument term length.
|
|
2373
|
+
*/
|
|
2374
|
+
longestArgumentTermLength(): number;
|
|
2375
|
+
/**
|
|
2376
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
2377
|
+
*/
|
|
2378
|
+
commandUsage(): string;
|
|
2379
|
+
/**
|
|
2380
|
+
* Get the description for the command.
|
|
2381
|
+
*/
|
|
2382
|
+
commandDescription(): string;
|
|
2383
|
+
/**
|
|
2384
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
2385
|
+
* (Fallback to description for backwards compatibility.)
|
|
2386
|
+
*/
|
|
2387
|
+
subcommandDescription(sub: ICommand): string;
|
|
2388
|
+
/**
|
|
2389
|
+
* Get the option description to show in the list of options.
|
|
2390
|
+
*/
|
|
2391
|
+
optionDescription(option: Option): string;
|
|
2392
|
+
/**
|
|
2393
|
+
* Get the argument description to show in the list of arguments.
|
|
2394
|
+
*/
|
|
2395
|
+
argumentDescription(argument: Argument): string;
|
|
2396
|
+
/**
|
|
2397
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
2398
|
+
*/
|
|
2399
|
+
formatItemList(heading: string, items: string[]): string[];
|
|
2400
|
+
/**
|
|
2401
|
+
* Group items by their help group heading.
|
|
2402
|
+
*/
|
|
2403
|
+
groupItems<T extends ICommand | Option>(unsortedItems: T[], visibleItems: T[], getGroup: (item: T) => string): Map<string, T[]>;
|
|
2404
|
+
/**
|
|
2405
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
2406
|
+
*/
|
|
2407
|
+
displayWidth(str: string): number;
|
|
2408
|
+
/**
|
|
2409
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
2410
|
+
*/
|
|
2411
|
+
styleTitle(str: string): string;
|
|
2412
|
+
/**
|
|
2413
|
+
* Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
|
|
2414
|
+
*/
|
|
2415
|
+
styleUsage(str: string): string;
|
|
2416
|
+
/**
|
|
2417
|
+
* Style command descriptions for display in help output.
|
|
2418
|
+
*/
|
|
2419
|
+
styleCommandDescription(str: string): string;
|
|
2420
|
+
/**
|
|
2421
|
+
* Style option descriptions for display in help output.
|
|
2422
|
+
*/
|
|
2423
|
+
styleOptionDescription(str: string): string;
|
|
2424
|
+
/**
|
|
2425
|
+
* Style subcommand descriptions for display in help output.
|
|
2426
|
+
*/
|
|
2427
|
+
styleSubcommandDescription(str: string): string;
|
|
2428
|
+
/**
|
|
2429
|
+
* Style argument descriptions for display in help output.
|
|
2430
|
+
*/
|
|
2431
|
+
styleArgumentDescription(str: string): string;
|
|
2432
|
+
/**
|
|
2433
|
+
* Base style used by descriptions. Override in subclass to apply custom formatting.
|
|
2434
|
+
*/
|
|
2435
|
+
styleDescriptionText(str: string): string;
|
|
2436
|
+
/**
|
|
2437
|
+
* Style option terms (flags) for display in help output.
|
|
2438
|
+
*/
|
|
2439
|
+
styleOptionTerm(str: string): string;
|
|
2440
|
+
/**
|
|
2441
|
+
* Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
|
|
2442
|
+
*/
|
|
2443
|
+
styleSubcommandTerm(str: string): string;
|
|
2444
|
+
/**
|
|
2445
|
+
* Style argument terms for display in help output.
|
|
2446
|
+
*/
|
|
2447
|
+
styleArgumentTerm(str: string): string;
|
|
2448
|
+
/**
|
|
2449
|
+
* Base style used in terms and usage for options. Override in subclass to apply custom formatting.
|
|
2450
|
+
*/
|
|
2451
|
+
styleOptionText(str: string): string;
|
|
2452
|
+
/**
|
|
2453
|
+
* Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
|
|
2454
|
+
*/
|
|
2455
|
+
styleArgumentText(str: string): string;
|
|
2456
|
+
/**
|
|
2457
|
+
* Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
|
|
2458
|
+
*/
|
|
2459
|
+
styleSubcommandText(str: string): string;
|
|
2460
|
+
/**
|
|
2461
|
+
* Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
|
|
2462
|
+
*/
|
|
2463
|
+
styleCommandText(str: string): string;
|
|
2464
|
+
/**
|
|
2465
|
+
* Calculate the pad width from the maximum term length.
|
|
2466
|
+
*/
|
|
2467
|
+
padWidth(): number;
|
|
2468
|
+
/**
|
|
2469
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
2470
|
+
*/
|
|
2471
|
+
preformatted(str: string): boolean;
|
|
2472
|
+
/**
|
|
2473
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
2474
|
+
*
|
|
2475
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
2476
|
+
* TTT DDD DDDD
|
|
2477
|
+
* DD DDD
|
|
2478
|
+
*/
|
|
2479
|
+
formatItem(term: string, termWidth: number, description: string): string;
|
|
2480
|
+
/**
|
|
2481
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
2482
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
2483
|
+
*/
|
|
2484
|
+
boxWrap(str: string, width: number): string;
|
|
2485
|
+
/**
|
|
2486
|
+
* Generate the built-in help text.
|
|
2487
|
+
*/
|
|
2488
|
+
render(): string;
|
|
2489
|
+
}
|
|
2490
|
+
/** Action handler function type, which receives parsed arguments and options as well as metadata about the command execution context. */
|
|
2491
|
+
type ActionHandler<A extends Arguments, O extends Options, Subs extends SubCommands> = (...args: [
|
|
2492
|
+
...A,
|
|
2493
|
+
O,
|
|
2494
|
+
{
|
|
2495
|
+
path: string[];
|
|
2496
|
+
name: string;
|
|
2497
|
+
argv: string[];
|
|
2498
|
+
args: A;
|
|
2499
|
+
opts: O;
|
|
2500
|
+
errors?: string[];
|
|
2501
|
+
cmd: Command<A, O, Subs>;
|
|
2502
|
+
logger: Logger;
|
|
2503
|
+
}
|
|
2504
|
+
]) => Promise<void> | void;
|
|
2505
|
+
/** Predicate function type for hooks, which receives the same metadata as action handlers and returns a boolean indicating whether the hook's action should be executed. */
|
|
2506
|
+
type HookPredicate<A extends Arguments = Arguments, O extends Options = Options, Subs extends SubCommands = SubCommands> = (data: {
|
|
2507
|
+
path: string[];
|
|
2508
|
+
name: string;
|
|
2509
|
+
argv: string[];
|
|
2510
|
+
args: A;
|
|
2511
|
+
opts: O;
|
|
2512
|
+
errors?: string[];
|
|
2513
|
+
cmd: Command<A, O, Subs>;
|
|
2514
|
+
}) => boolean;
|
|
2515
|
+
/** Action handler function type for hooks, which receives the same metadata as action handlers and is executed when its predicate returns true. Can also throw to indicate an error. */
|
|
2516
|
+
type HookActionHandler<A extends Arguments = Arguments, O extends Options = Options, Subs extends SubCommands = SubCommands> = (data: {
|
|
2517
|
+
path: string[];
|
|
2518
|
+
name: string;
|
|
2519
|
+
argv: string[];
|
|
2520
|
+
args: A;
|
|
2521
|
+
opts: O;
|
|
2522
|
+
errors?: string[];
|
|
2523
|
+
cmd: Command<A, O, Subs>;
|
|
2524
|
+
}) => Promise<void> | void | never;
|
|
2525
|
+
/** Hook definition type, which includes the option name that triggers the hook, a predicate function to determine when the hook should run, and an action handler to execute when triggered. */
|
|
2526
|
+
type HookDefinition<A extends Arguments = Arguments, O extends Options = Options, Subs extends SubCommands = SubCommands> = {
|
|
2527
|
+
name: keyof O;
|
|
2528
|
+
predicate: HookPredicate<A, O, Subs>;
|
|
2529
|
+
action: HookActionHandler<A, O, Subs>;
|
|
2530
|
+
};
|
|
2531
|
+
/**
|
|
2532
|
+
* @see Command.prototype.parseArgv
|
|
2533
|
+
*/
|
|
2534
|
+
type ParseArgvResult<A extends Arguments = Arguments, O extends Options = Options, Subs extends SubCommands = SubCommands> = {
|
|
2535
|
+
/** The command or subcommand instance */
|
|
2536
|
+
get cmd(): Command<A, O, Subs>;
|
|
2537
|
+
/** The part of argv that makes out a subcommand path, or empty array when root command */
|
|
2538
|
+
path: string[];
|
|
2539
|
+
/** Command namer */
|
|
2540
|
+
name: string;
|
|
2541
|
+
/** Original argv array passed in or from process.argv, excluding subcommand path */
|
|
2542
|
+
argv: string[];
|
|
2543
|
+
/** Parsed arguments */
|
|
2544
|
+
args: A;
|
|
2545
|
+
/** Parsed options */
|
|
2546
|
+
opts: O;
|
|
2547
|
+
/** Error messages if parsing failed, otherwise undefined */
|
|
2548
|
+
errors?: string[];
|
|
2549
|
+
/** Names of all triggered hooks whose predicate returned true */
|
|
2550
|
+
hooks: HookDefinition<A, O, Subs>[];
|
|
2551
|
+
/** Calls the action handler with its expected args */
|
|
2552
|
+
execute: () => Promise<void>;
|
|
2553
|
+
};
|
|
2554
|
+
/** required variadic argument */
|
|
2555
|
+
type RequiredVariadicArgumentUsage = `<${string}...>`;
|
|
2556
|
+
/** optional variadic argument */
|
|
2557
|
+
type OptionalVariadicArgumentUsage = `[${string}...]`;
|
|
2558
|
+
/** required argument */
|
|
2559
|
+
type RequiredArgumentUsage = `<${string}>`;
|
|
2560
|
+
/** optional argument */
|
|
2561
|
+
type OptionalArgumentUsage = `[${string}]`;
|
|
2562
|
+
/** Union of all argument usage pattern types */
|
|
2563
|
+
type ArgumentUsage = RequiredVariadicArgumentUsage | OptionalVariadicArgumentUsage | RequiredArgumentUsage | OptionalArgumentUsage;
|
|
2564
|
+
/** Helper type to infer allowed argument usage patterns based on the command's existing argument types */
|
|
2565
|
+
type InferArgumentUsage<T extends Command<any, any, any>> = T extends Command<infer A, any> ? A extends string[] ? ArgumentUsage : A extends (string | (string | undefined))[] ? OptionalArgumentUsage | OptionalVariadicArgumentUsage : never : never;
|
|
2566
|
+
/** Helper type to infer allowed argument usage patterns based on the command's existing argument types */
|
|
2567
|
+
type AllowedArgumentUsage<T extends Command<any, any, any>, Usage extends ArgumentUsage> = Usage extends InferArgumentUsage<T> ? Usage : never;
|
|
2568
|
+
/** Base type for addArgument options, extended by specific required/optional and variadic/non-variadic argument option types */
|
|
2569
|
+
type ArgumentOptionsBase = Omit<Argument, 'name' | 'required' | 'variadic' | 'usage' | 'defaultValue' | 'defaultValueDescription'>;
|
|
2570
|
+
/** Base type for addArgument options, extended by specific required/optional and variadic/non-variadic argument option types */
|
|
2571
|
+
type ExtendArgumentOptionsBase<T extends object = object> = Simplify<ArgumentOptionsBase & T>;
|
|
2572
|
+
/** Required positional argument descriptor. Usage: `<name>` */
|
|
2573
|
+
type RequiredArgumentOptions = ExtendArgumentOptionsBase;
|
|
2574
|
+
/** Optional positional argument with string default. Usage: `[name]` */
|
|
2575
|
+
type OptionalArgumentOptions = ExtendArgumentOptionsBase<{
|
|
2576
|
+
defaultValue?: string;
|
|
2577
|
+
defaultValueDescription?: string;
|
|
2578
|
+
}>;
|
|
2579
|
+
/** Optional positional argument with required string default. Usage: `[name]` */
|
|
2580
|
+
type OptionalArgumentOptionsWithDefaultValue = SetFieldType<SetRequired<OptionalArgumentOptions, 'defaultValue'>, 'defaultValue', string>;
|
|
2581
|
+
/** Required variadic argument accepting variadic values. Usage: `<name...>` */
|
|
2582
|
+
type RequiredVariadicArgumentOptions = ExtendArgumentOptionsBase;
|
|
2583
|
+
/** Optional variadic argument with array default. Usage: `[name...]` */
|
|
2584
|
+
type OptionalVariadicArgumentOptions = ExtendArgumentOptionsBase<{
|
|
2585
|
+
defaultValue?: string[];
|
|
2586
|
+
defaultValueDescription?: string;
|
|
2587
|
+
}>;
|
|
2588
|
+
/** Union of all addArgument options types */
|
|
2589
|
+
type ArgumentOptions = AllUnionFields<RequiredArgumentOptions | OptionalArgumentOptions | OptionalArgumentOptionsWithDefaultValue | RequiredVariadicArgumentOptions | OptionalVariadicArgumentOptions>;
|
|
2590
|
+
/** Helper type for extracting argument name from usage pattern */
|
|
2591
|
+
type InferAddedArgumentType<Opts> = Opts extends {
|
|
2592
|
+
choices: infer C extends string[];
|
|
2593
|
+
} ? C[number] : string;
|
|
2594
|
+
/** Union of all option usage pattern types */
|
|
2595
|
+
type OptionUsage<Long extends string> = `-${string}, --${Long}` | `-${string}, --${Long} <${string}>` | `-${string}, --${Long} [${string}]` | `-${string}, --${Long} <${string}...>` | `-${string}, --${Long} [${string}...]`;
|
|
2596
|
+
/** Base type for addOption options, extended by specific boolean/string and required/optional and variadic/non-variadic option types */
|
|
2597
|
+
type OptionOptionsBase = Omit<Option, 'name' | 'required' | 'variadic' | 'type' | 'argName' | 'short' | 'long' | 'flags'>;
|
|
2598
|
+
/** Helper type to extend base addOption options with specific fields for different option types */
|
|
2599
|
+
type ExtendAddOptionOptionsBase<T extends object = object> = Simplify<OptionOptionsBase & T>;
|
|
2600
|
+
/** Boolean flag option. Usage: `-v, --verbose` */
|
|
2601
|
+
type BooleanOptionOptions = ExtendAddOptionOptionsBase<{
|
|
2602
|
+
defaultValue?: boolean;
|
|
2603
|
+
defaultValueDescription?: string;
|
|
2604
|
+
}>;
|
|
2605
|
+
/** Required string option. Usage: `-f, --file <path>` */
|
|
2606
|
+
type RequiredOptionOptions = ExtendAddOptionOptionsBase<{
|
|
2607
|
+
env?: undefined;
|
|
2608
|
+
}>;
|
|
2609
|
+
/** Optional string option with default. Usage: `-o, --output [path]` */
|
|
2610
|
+
type OptionalOptionOptions = ExtendAddOptionOptionsBase<{
|
|
2611
|
+
defaultValue?: string;
|
|
2612
|
+
defaultValueDescription?: string;
|
|
2613
|
+
}>;
|
|
2614
|
+
/** Required option accepting variadic values. Usage: `-i, --include <patterns...>` */
|
|
2615
|
+
type RequiredVariadicOptionOptions = ExtendAddOptionOptionsBase<{
|
|
2616
|
+
env?: undefined;
|
|
2617
|
+
}>;
|
|
2618
|
+
/** Optional option accepting variadic values with defaults. Usage: `-e, --exclude [patterns...]` */
|
|
2619
|
+
type OptionalVariadicOptionOptions = ExtendAddOptionOptionsBase<{
|
|
2620
|
+
defaultValue?: string[];
|
|
2621
|
+
defaultValueDescription?: string;
|
|
2622
|
+
}>;
|
|
2623
|
+
/** Union of all addOption options types */
|
|
2624
|
+
type OptionOptions = AllUnionFields<BooleanOptionOptions | RequiredOptionOptions | OptionalOptionOptions | RequiredVariadicOptionOptions | OptionalVariadicOptionOptions>;
|
|
2625
|
+
/** Helper type to infer the resulting Command type after adding an option with specific options */
|
|
2626
|
+
type InferAddOptionResult<A extends Arguments, O extends Options, NewOptions extends Options, Subs extends SubCommands> = Command<A, Simplify<O & NewOptions>, Subs>;
|
|
2627
|
+
|
|
2628
|
+
/**
|
|
2629
|
+
* Parses option flags string into its components
|
|
2630
|
+
*/
|
|
2631
|
+
declare function parseOptionFlags<Long extends string>(flags: OptionUsage<Long>): {
|
|
2632
|
+
short: string;
|
|
2633
|
+
long: Long;
|
|
2634
|
+
name: CamelCase<Long>;
|
|
2635
|
+
argName: string | undefined;
|
|
2636
|
+
};
|
|
2637
|
+
|
|
2638
|
+
/**
|
|
2639
|
+
* Returns command and all ancestor commands in hierarchy
|
|
2640
|
+
*/
|
|
2641
|
+
declare function getCommandAndAncestors<C extends ICommand>(cmd: C): [typeof cmd, ...ICommand[]];
|
|
2642
|
+
|
|
2643
|
+
/**
|
|
2644
|
+
* Returns all ancestor commands excluding this command
|
|
2645
|
+
*/
|
|
2646
|
+
declare function getCommandAncestors<C extends ICommand>(cmd: C): C[];
|
|
2647
|
+
|
|
2648
|
+
/**
|
|
2649
|
+
* Finds option by name, short name or long name
|
|
2650
|
+
*/
|
|
2651
|
+
declare function findOption<C extends ICommand>(cmd: C, nameOrShortOrLong: string): Option | undefined;
|
|
2652
|
+
|
|
2653
|
+
/**
|
|
2654
|
+
* Finds subcommand by name or alias
|
|
2655
|
+
*/
|
|
2656
|
+
declare function findCommand<C extends Command = Command>(cmd: ICommand, nameOrAlias: string): C | undefined;
|
|
2657
|
+
|
|
2658
|
+
export { type ActionHandler, type AllowedArgumentUsage, type Argument, type ArgumentOptions, type ArgumentUsage, type Arguments, type BooleanOptionOptions, Command, Help, type HookActionHandler, type HookDefinition, type HookPredicate, type ICommand, type IHelp, type InferAddOptionResult, type InferAddedArgumentType, type Logger, type Option, type OptionOptions, type OptionUsage, type OptionalArgumentOptions, type OptionalArgumentOptionsWithDefaultValue, type OptionalArgumentUsage, type OptionalOptionOptions, type OptionalVariadicArgumentOptions, type OptionalVariadicArgumentUsage, type OptionalVariadicOptionOptions, type Options, type ParseArgvResult, type RequiredArgumentOptions, type RequiredArgumentUsage, type RequiredOptionOptions, type RequiredVariadicArgumentOptions, type RequiredVariadicArgumentUsage, type RequiredVariadicOptionOptions, type SubCommands, findCommand, findOption, getCommandAncestors, getCommandAndAncestors, parseOptionFlags };
|