@bemoje/cli 5.0.2 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +36 -32
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +2387 -1104
- package/lib/index.d.ts +2387 -1104
- package/lib/index.js +36 -32
- package/lib/index.js.map +1 -0
- package/package.json +7 -5
package/lib/index.d.ts
CHANGED
|
@@ -13,242 +13,187 @@ type Primitive =
|
|
|
13
13
|
| bigint;
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
|
-
|
|
16
|
+
Tries to find the type of a global with the given name.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Limitations: Due to peculiarities with the behavior of `globalThis`, "globally defined" only includes `var` declarations in `declare global` blocks, not `let` or `const` declarations.
|
|
19
19
|
|
|
20
20
|
@example
|
|
21
21
|
```
|
|
22
|
-
import type {
|
|
22
|
+
import type {FindGlobalType} from 'type-fest';
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
declare global {
|
|
25
|
+
const foo: number; // let and const don't work
|
|
26
|
+
var bar: string; // var works
|
|
27
|
+
}
|
|
25
28
|
|
|
26
|
-
type
|
|
27
|
-
|
|
29
|
+
type FooType = FindGlobalType<'foo'>; //=> never (let/const don't work)
|
|
30
|
+
type BarType = FindGlobalType<'bar'>; //=> string
|
|
31
|
+
type OtherType = FindGlobalType<'other'>; //=> never (no global named 'other')
|
|
28
32
|
```
|
|
29
33
|
|
|
30
|
-
@category
|
|
34
|
+
@category Utilities
|
|
31
35
|
*/
|
|
32
|
-
type
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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;
|
|
36
|
+
type FindGlobalType<Name extends string> =
|
|
37
|
+
Name extends string // For distributing `Name`, so a missing global does not discard the globals found for other names.
|
|
38
|
+
? typeof globalThis extends Record<Name, infer T> ? T : never
|
|
39
|
+
: never;
|
|
48
40
|
|
|
49
41
|
/**
|
|
50
|
-
|
|
42
|
+
Tries to find one or more types from their globally-defined constructors.
|
|
51
43
|
|
|
52
|
-
|
|
44
|
+
Use-case: Conditionally referencing DOM types only when the DOM library present.
|
|
53
45
|
|
|
54
|
-
|
|
46
|
+
Limitations: Due to peculiarities with the behavior of `globalThis`, "globally defined" has a narrow definition in this case. Declaring a class in a `declare global` block won't work, instead you must declare its type using an interface and declare its constructor as a `var` (*not* `let`/`const`) inside the `declare global` block.
|
|
55
47
|
|
|
56
48
|
@example
|
|
57
49
|
```
|
|
58
|
-
import type {
|
|
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;
|
|
50
|
+
import type {FindGlobalInstanceType} from 'type-fest';
|
|
76
51
|
|
|
77
|
-
|
|
78
|
-
|
|
52
|
+
class Point {
|
|
53
|
+
constructor(public x: number, public y: number) {}
|
|
54
|
+
}
|
|
79
55
|
|
|
80
|
-
type
|
|
81
|
-
//=> 'common' | 'a' | 'b' | 'c'
|
|
56
|
+
type PointLike = Point | FindGlobalInstanceType<'DOMPoint'>;
|
|
82
57
|
```
|
|
83
58
|
|
|
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
59
|
@example
|
|
98
60
|
```
|
|
99
|
-
import type {
|
|
61
|
+
import type {FindGlobalInstanceType} from 'type-fest';
|
|
100
62
|
|
|
101
|
-
|
|
102
|
-
|
|
63
|
+
declare global {
|
|
64
|
+
// Class syntax won't add the key to `globalThis`
|
|
65
|
+
class Foo {}
|
|
103
66
|
|
|
104
|
-
|
|
105
|
-
|
|
67
|
+
// interface + constructor style works
|
|
68
|
+
interface Bar {
|
|
69
|
+
bar: string;
|
|
70
|
+
}
|
|
71
|
+
var Bar: new () => Bar; // Not let or const
|
|
106
72
|
}
|
|
107
73
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const anyA = get(anyObject, 'a');
|
|
112
|
-
//=> any
|
|
74
|
+
type FindFoo = FindGlobalInstanceType<'Foo'>; // Doesn't work
|
|
75
|
+
type FindBar = FindGlobalInstanceType<'Bar'>; // Works
|
|
113
76
|
```
|
|
114
77
|
|
|
115
|
-
@category Type Guard
|
|
116
78
|
@category Utilities
|
|
117
79
|
*/
|
|
118
|
-
type
|
|
80
|
+
type FindGlobalInstanceType<Name extends string> =
|
|
81
|
+
Name extends string
|
|
82
|
+
? typeof globalThis extends Record<Name, abstract new (...arguments_: any[]) => infer T> ? T : never
|
|
83
|
+
: never;
|
|
119
84
|
|
|
120
85
|
/**
|
|
121
|
-
|
|
86
|
+
Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
|
|
87
|
+
|
|
88
|
+
Use the `Buffer` type parameter to require a specific buffer type. For example, `TypedArray<ArrayBuffer>` excludes views of a `SharedArrayBuffer`, which APIs that take a `BufferSource`, like `crypto.subtle.digest()`, do not accept.
|
|
122
89
|
|
|
123
|
-
|
|
90
|
+
`Float16Array` is included only when it exists in your TypeScript `lib` (`ESNext` or `ES2025` and later) or is added by `@types/node`.
|
|
124
91
|
|
|
125
92
|
@example
|
|
126
93
|
```
|
|
127
|
-
import type {
|
|
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
|
|
94
|
+
import type {TypedArray} from 'type-fest';
|
|
143
95
|
|
|
144
|
-
|
|
145
|
-
//=> false
|
|
146
|
-
|
|
147
|
-
type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>;
|
|
148
|
-
//=> boolean
|
|
96
|
+
declare function hash(data: TypedArray<ArrayBuffer>): Promise<ArrayBuffer>;
|
|
149
97
|
|
|
150
|
-
|
|
151
|
-
//=> false
|
|
98
|
+
void hash(new Uint8Array(8));
|
|
152
99
|
|
|
153
|
-
|
|
154
|
-
|
|
100
|
+
// @ts-expect-error
|
|
101
|
+
void hash(new Uint8Array(new SharedArrayBuffer(8)));
|
|
155
102
|
```
|
|
156
103
|
|
|
157
|
-
@category
|
|
158
|
-
@category Utilities
|
|
104
|
+
@category Array
|
|
159
105
|
*/
|
|
160
|
-
type
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
106
|
+
type TypedArray<Buffer extends ArrayBufferLike = ArrayBufferLike> =
|
|
107
|
+
| Int8Array<Buffer>
|
|
108
|
+
| Uint8Array<Buffer>
|
|
109
|
+
| Uint8ClampedArray<Buffer>
|
|
110
|
+
| Int16Array<Buffer>
|
|
111
|
+
| Uint16Array<Buffer>
|
|
112
|
+
| Int32Array<Buffer>
|
|
113
|
+
| Uint32Array<Buffer>
|
|
114
|
+
| Float16ArrayOf<Buffer>
|
|
115
|
+
| Float32Array<Buffer>
|
|
116
|
+
| Float64Array<Buffer>
|
|
117
|
+
| BigInt64Array<Buffer>
|
|
118
|
+
| BigUint64Array<Buffer>;
|
|
167
119
|
|
|
168
120
|
/**
|
|
169
|
-
|
|
121
|
+
`Float16Array` is looked up through `globalThis`, so that a `lib` without it gets `never` here instead of a compile error. The `prototype` type is `Float16Array<ArrayBufferLike>`, and a type cannot pass `Buffer` to an interface it cannot name, so the members that use the buffer type are narrowed instead. `subarray()` must be narrowed too, because `@types/node` defines `BufferSource` with `Float16Array<ArrayBuffer>`. The narrowed members come first, so that `subarray()` resolves to them.
|
|
122
|
+
*/
|
|
123
|
+
type Float16ArrayOf<Buffer extends ArrayBufferLike> = {
|
|
124
|
+
readonly buffer: Buffer;
|
|
125
|
+
subarray(begin?: number, end?: number): Float16ArrayOf<Buffer>;
|
|
126
|
+
} & FindGlobalType<'Float16Array'>['prototype'];
|
|
170
127
|
|
|
171
|
-
|
|
128
|
+
/**
|
|
129
|
+
Matches any digit as a string ('0'-'9').
|
|
172
130
|
|
|
173
131
|
@example
|
|
174
132
|
```
|
|
175
|
-
import type {
|
|
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
|
-
};
|
|
133
|
+
import type {DigitCharacter} from 'type-fest';
|
|
188
134
|
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const update2: UpdateOperation<User> = {
|
|
194
|
-
name: 'Bob',
|
|
195
|
-
luckyNumber: REMOVE_FIELD,
|
|
196
|
-
};
|
|
135
|
+
const a: DigitCharacter = '0'; // Valid
|
|
136
|
+
// @ts-expect-error
|
|
137
|
+
const b: DigitCharacter = 0; // Invalid
|
|
197
138
|
```
|
|
198
139
|
|
|
199
|
-
@category
|
|
140
|
+
@category Type
|
|
200
141
|
*/
|
|
201
|
-
type
|
|
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
|
|
142
|
+
type DigitCharacter = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
|
|
210
143
|
|
|
211
144
|
/**
|
|
212
|
-
|
|
145
|
+
Create a union of all keys from a given type, even those exclusive to specific union members.
|
|
213
146
|
|
|
214
|
-
|
|
147
|
+
Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
|
|
148
|
+
|
|
149
|
+
@see https://stackoverflow.com/a/49402091
|
|
215
150
|
|
|
216
151
|
@example
|
|
217
152
|
```
|
|
218
|
-
import type {
|
|
153
|
+
import type {KeysOfUnion} from 'type-fest';
|
|
219
154
|
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
155
|
+
type A = {
|
|
156
|
+
common: string;
|
|
157
|
+
a: number;
|
|
158
|
+
};
|
|
224
159
|
|
|
225
|
-
type
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
luckyNumber?: number;
|
|
160
|
+
type B = {
|
|
161
|
+
common: string;
|
|
162
|
+
b: string;
|
|
229
163
|
};
|
|
230
164
|
|
|
231
|
-
|
|
232
|
-
|
|
165
|
+
type C = {
|
|
166
|
+
common: string;
|
|
167
|
+
c: boolean;
|
|
168
|
+
};
|
|
233
169
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
170
|
+
type Union = A | B | C;
|
|
171
|
+
|
|
172
|
+
type CommonKeys = keyof Union;
|
|
173
|
+
//=> 'common'
|
|
174
|
+
|
|
175
|
+
type AllKeys = KeysOfUnion<Union>;
|
|
176
|
+
//=> 'common' | 'a' | 'b' | 'c'
|
|
237
177
|
```
|
|
238
178
|
|
|
239
|
-
@category
|
|
179
|
+
@category Object
|
|
240
180
|
*/
|
|
241
|
-
type
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
181
|
+
type KeysOfUnion<ObjectType> =
|
|
182
|
+
// Adds no keys, since these are the keys all members share, but it lets the compiler accept a key narrowed with `keyof` when `ObjectType` is generic, such as a conditional type that is not resolved yet.
|
|
183
|
+
| keyof ObjectType
|
|
184
|
+
// Infer a union of each member's keys from function return types.
|
|
185
|
+
// This avoids the record intersections and extra `& Union` that `UnionToIntersection` would create.
|
|
186
|
+
// The outer conditional prevents unresolved generic union keys from being treated as safe to index every member.
|
|
187
|
+
| ((ObjectType extends unknown ? () => keyof ObjectType : never) extends (() => infer Keys extends PropertyKey)
|
|
188
|
+
? Keys
|
|
189
|
+
: never);
|
|
245
190
|
|
|
246
191
|
/**
|
|
247
192
|
Returns a boolean for whether the given type is `never`.
|
|
248
193
|
|
|
249
|
-
@
|
|
250
|
-
@
|
|
251
|
-
@
|
|
194
|
+
@see https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
|
|
195
|
+
@see https://stackoverflow.com/a/53984913/10292952
|
|
196
|
+
@see https://www.zhenghao.io/posts/ts-never
|
|
252
197
|
|
|
253
198
|
Useful in type utilities, such as checking if something does not occur.
|
|
254
199
|
|
|
@@ -299,219 +244,810 @@ type B = IsTrueFixed<never>;
|
|
|
299
244
|
type IsNever<T> = [T] extends [never] ? true : false;
|
|
300
245
|
|
|
301
246
|
/**
|
|
302
|
-
|
|
247
|
+
Returns a boolean for whether the given type is `any`.
|
|
303
248
|
|
|
304
|
-
|
|
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'>`.
|
|
249
|
+
Returns `false` for `never` and `unknown`. Unions are normalized before the check.
|
|
306
250
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
251
|
+
@see https://stackoverflow.com/a/49928360/1490091
|
|
252
|
+
|
|
253
|
+
Useful in type utilities, such as disallowing `any`s to be passed to a function.
|
|
310
254
|
|
|
311
255
|
@example
|
|
312
256
|
```
|
|
313
|
-
import type {
|
|
314
|
-
|
|
315
|
-
type A = If<true, 'yes', 'no'>;
|
|
316
|
-
//=> 'yes'
|
|
257
|
+
import type {IsAny} from 'type-fest';
|
|
317
258
|
|
|
318
|
-
|
|
319
|
-
|
|
259
|
+
const typedObject = {a: 1, b: 2} as const;
|
|
260
|
+
const anyObject: any = {a: 1, b: 2};
|
|
320
261
|
|
|
321
|
-
|
|
322
|
-
|
|
262
|
+
function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(object: O, key: K) {
|
|
263
|
+
return object[key];
|
|
264
|
+
}
|
|
323
265
|
|
|
324
|
-
|
|
325
|
-
//=>
|
|
266
|
+
const typedA = get(typedObject, 'a');
|
|
267
|
+
//=> 1
|
|
326
268
|
|
|
327
|
-
|
|
328
|
-
//=>
|
|
269
|
+
const anyA = get(anyObject, 'a');
|
|
270
|
+
//=> any
|
|
329
271
|
```
|
|
330
272
|
|
|
331
|
-
@
|
|
332
|
-
|
|
333
|
-
|
|
273
|
+
@category Type Guard
|
|
274
|
+
@category Utilities
|
|
275
|
+
*/
|
|
276
|
+
type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
|
|
334
277
|
|
|
335
|
-
|
|
336
|
-
//=> 'not any'
|
|
278
|
+
declare const tag: unique symbol;
|
|
337
279
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
280
|
+
/**
|
|
281
|
+
Returns an arbitrary member of a union type.
|
|
282
|
+
|
|
283
|
+
Use-cases:
|
|
284
|
+
- Implementing recursive type functions that accept a union type.
|
|
341
285
|
|
|
342
286
|
@example
|
|
343
287
|
```
|
|
344
|
-
import type {
|
|
288
|
+
import type {UnionMember, IsNever} from 'type-fest';
|
|
345
289
|
|
|
346
|
-
type
|
|
290
|
+
type UnionLength<T, Acc extends any[] = []> =
|
|
291
|
+
UnionMember<T> extends infer Member
|
|
292
|
+
? IsNever<Member> extends false
|
|
293
|
+
? UnionLength<Exclude<T, Member>, [...Acc, Member]>
|
|
294
|
+
: Acc['length']
|
|
295
|
+
: never;
|
|
347
296
|
|
|
348
|
-
type
|
|
349
|
-
//=>
|
|
297
|
+
type T1 = UnionLength<'foo' | 'bar' | 'baz'>;
|
|
298
|
+
//=> 3
|
|
350
299
|
|
|
351
|
-
type
|
|
352
|
-
//=>
|
|
300
|
+
type T2 = UnionLength<{a: string}>;
|
|
301
|
+
//=> 1
|
|
353
302
|
```
|
|
354
303
|
|
|
355
|
-
|
|
304
|
+
- Picking an arbitrary member from a union
|
|
356
305
|
|
|
357
306
|
@example
|
|
358
307
|
```
|
|
359
|
-
import type {
|
|
308
|
+
import type {UnionMember, Primitive, LiteralToPrimitive} from 'type-fest';
|
|
360
309
|
|
|
361
|
-
type
|
|
310
|
+
type IsHomogenous<T extends Primitive> = [T] extends [LiteralToPrimitive<UnionMember<T>>] ? true : false;
|
|
362
311
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
S extends `${infer First}${infer Rest}`
|
|
366
|
-
? If<IsEqual<First, Char>,
|
|
367
|
-
'found',
|
|
368
|
-
Includes<Rest, Char>>
|
|
369
|
-
: 'not found';
|
|
312
|
+
type T1 = IsHomogenous<1 | 2 | 3 | 4>;
|
|
313
|
+
//=> true
|
|
370
314
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
type Fails = Includes<HundredZeroes, '1'>;
|
|
374
|
-
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
375
|
-
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
315
|
+
type T2 = IsHomogenous<'foo' | 'bar'>;
|
|
316
|
+
//=> true
|
|
376
317
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
? IsEqual<First, Char> extends true
|
|
381
|
-
? 'found'
|
|
382
|
-
: IncludesWithoutIf<Rest, Char>
|
|
383
|
-
: 'not found';
|
|
318
|
+
type T3 = IsHomogenous<'foo' | 'bar' | 1>;
|
|
319
|
+
//=> false
|
|
320
|
+
```
|
|
384
321
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
322
|
+
Returns `never` when the input is `never`.
|
|
323
|
+
|
|
324
|
+
@example
|
|
388
325
|
```
|
|
326
|
+
import type {UnionMember} from 'type-fest';
|
|
389
327
|
|
|
390
|
-
|
|
391
|
-
|
|
328
|
+
type LastNever = UnionMember<never>;
|
|
329
|
+
//=> never
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
@category Type
|
|
392
333
|
*/
|
|
393
|
-
type
|
|
394
|
-
IsNever<
|
|
395
|
-
?
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
334
|
+
type UnionMember<T> =
|
|
335
|
+
IsNever<T> extends true
|
|
336
|
+
? never
|
|
337
|
+
// This infers the intersection itself instead of using `UnionToIntersection`, whose `& Union` makes TypeScript distribute the intersection over every member, which is slow for large unions and for types like `Tagged` that call this in a loop.
|
|
338
|
+
: (T extends any ? (member: () => T) => void : never) extends (member: infer Intersection) => void
|
|
339
|
+
? Intersection extends () => (infer R)
|
|
340
|
+
? R
|
|
341
|
+
: never
|
|
342
|
+
: never;
|
|
343
|
+
|
|
344
|
+
// For `@link`
|
|
345
|
+
|
|
346
|
+
// Declaration emit cannot name the `tag` symbol unless the user's file imports it. So exporting a value whose inferred type contains the `[tag]` key directly (for example, after spreading a tagged object) fails with TS4023: https://github.com/microsoft/TypeScript/issues/64812
|
|
347
|
+
// eslint-disable-next-line type-fest/require-exported-types
|
|
348
|
+
type TagContainer<Token> = {
|
|
349
|
+
readonly [tag]: Token;
|
|
350
|
+
};
|
|
399
351
|
|
|
400
352
|
/**
|
|
401
|
-
|
|
353
|
+
The tag part of a {@link Tagged} type, without the underlying type.
|
|
402
354
|
|
|
403
|
-
|
|
355
|
+
`Tagged<Type, TagName, TagMetadata>` is `Type & Tag<TagName, TagMetadata>`. Use `Tagged` to create tagged types. Use `Tag` to accept any type that has a given tag, whatever its underlying type is.
|
|
356
|
+
|
|
357
|
+
TypeScript can also show a tagged type as an intersection with `Tag`, for example in emitted declaration files. This is why `Tag` is exported.
|
|
404
358
|
|
|
405
359
|
@example
|
|
406
360
|
```
|
|
407
|
-
import type {
|
|
361
|
+
import type {Tag, Tagged} from 'type-fest';
|
|
408
362
|
|
|
409
|
-
type
|
|
363
|
+
type Url = Tagged<string, 'URL'>;
|
|
364
|
+
type UrlObject = Tagged<URL, 'URL'>;
|
|
410
365
|
|
|
411
|
-
type
|
|
412
|
-
|
|
366
|
+
// Accepts any type that has the `URL` tag, with any metadata.
|
|
367
|
+
declare function fetchUrl(url: Tag<'URL', unknown>): void;
|
|
413
368
|
|
|
414
|
-
|
|
415
|
-
|
|
369
|
+
fetchUrl('https://example.com' as Url);
|
|
370
|
+
fetchUrl(new URL('https://example.com') as UrlObject);
|
|
416
371
|
|
|
417
|
-
|
|
418
|
-
|
|
372
|
+
// @ts-expect-error
|
|
373
|
+
fetchUrl('https://example.com');
|
|
419
374
|
```
|
|
420
375
|
|
|
421
376
|
@category Type
|
|
422
|
-
@category Array
|
|
423
377
|
*/
|
|
424
|
-
type
|
|
378
|
+
// Exported so that declaration emit can name it. TypeScript can reduce a `Tagged` type to `Type & Tag<…>` (for example, `Tagged<T, 'A'> & T`), and package `exports` hide this file, so a user's exported value with that type would otherwise fail with TS4023: https://github.com/sindresorhus/type-fest/pull/1243
|
|
379
|
+
type Tag<TagName extends PropertyKey, TagMetadata> = TagContainer<{[Key in TagName]: TagMetadata}>;
|
|
425
380
|
|
|
426
381
|
/**
|
|
427
|
-
|
|
428
|
-
*/
|
|
429
|
-
type BuiltIns = Primitive | void | Date | RegExp;
|
|
382
|
+
Get the untagged portion of a tagged type created with `Tagged`.
|
|
430
383
|
|
|
431
|
-
|
|
432
|
-
|
|
384
|
+
For nested tags, keep each tag’s metadata in one layer and add one distinct tag name per layer. Reusing a name with different metadata, or nesting multiple layers that each add several names, is not supported.
|
|
385
|
+
|
|
386
|
+
Why is this necessary?
|
|
387
|
+
|
|
388
|
+
1. Use a `Tagged` type as object keys
|
|
389
|
+
2. Prevent TS4058 error: "Return type of exported function has or is using name X from external module Y but cannot be named"
|
|
390
|
+
|
|
391
|
+
@example
|
|
392
|
+
```
|
|
393
|
+
import type {Tagged, UnwrapTagged} from 'type-fest';
|
|
394
|
+
|
|
395
|
+
type AccountType = Tagged<'SAVINGS' | 'CHECKING', 'AccountType'>;
|
|
396
|
+
|
|
397
|
+
const moneyByAccountType: Record<UnwrapTagged<AccountType>, number> = {
|
|
398
|
+
SAVINGS: 99,
|
|
399
|
+
CHECKING: 0.1,
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
// Without UnwrapTagged, the following expression would throw a type error.
|
|
403
|
+
const money = moneyByAccountType.SAVINGS; // TS error: Property 'SAVINGS' does not exist
|
|
404
|
+
|
|
405
|
+
// Attempting to pass a non-Tagged type to UnwrapTagged will raise a type error.
|
|
406
|
+
// @ts-expect-error
|
|
407
|
+
type WontWork = UnwrapTagged<string>;
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
@example
|
|
411
|
+
```
|
|
412
|
+
import type {Tagged, UnwrapTagged} from 'type-fest';
|
|
413
|
+
|
|
414
|
+
// Keep a tag’s metadata in one layer.
|
|
415
|
+
type CheckedUserId = Tagged<string, 'Checked', {parsed: true; validated: true}>;
|
|
416
|
+
|
|
417
|
+
type UserId = UnwrapTagged<CheckedUserId>;
|
|
418
|
+
//=> string
|
|
419
|
+
|
|
420
|
+
// Use a distinct tag name for another stage.
|
|
421
|
+
type StoredUserId = Tagged<CheckedUserId, 'Stored', {table: 'users'}>;
|
|
422
|
+
|
|
423
|
+
type StoredUserIdValue = UnwrapTagged<StoredUserId>;
|
|
424
|
+
//=> string
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
@category Type
|
|
428
|
+
*/
|
|
429
|
+
// The constraint accepts a bare `TagContainer` too, so that the deprecated `Opaque` form, which tags with a token rather than a keyed object, can be unwrapped as well.
|
|
430
|
+
type UnwrapTagged<TaggedType extends TagContainer<any>> =
|
|
431
|
+
RemoveAllTags<TaggedType>;
|
|
432
|
+
|
|
433
|
+
type RemoveAllTags<T> = T extends TagContainer<any>
|
|
434
|
+
// Every order of removing the tags ends at the same type, so following only one of them avoids branching recursively over every removal order.
|
|
435
|
+
? RemoveAllTags<UnionMember<RemoveTag<T>>>
|
|
436
|
+
: T;
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
Removes a single tag from `T`, returning every possible result.
|
|
440
|
+
|
|
441
|
+
A tag can be applied one tag-name at a time (each application contributes its own layer to the intersection) or as a union of tag names in a single application (one layer holding a multi-key tag object). Because the intersection is only stripped when a layer matches a target tag object exactly, both shapes are peeled here, and only strictly smaller results are kept so that the recursion always makes progress and terminates.
|
|
442
|
+
*/
|
|
443
|
+
type RemoveTag<T extends TagContainer<unknown>> =
|
|
444
|
+
| {
|
|
445
|
+
[ThisTag in keyof T[typeof tag]]: T extends infer Underlying & Tag<ThisTag, T[typeof tag][ThisTag]>
|
|
446
|
+
? [Underlying] extends [T] ? never : Underlying
|
|
447
|
+
: never
|
|
448
|
+
}[keyof T[typeof tag]]
|
|
449
|
+
| (T extends infer Underlying & TagContainer<T[typeof tag]>
|
|
450
|
+
? [Underlying] extends [T] ? never : Underlying
|
|
451
|
+
: never);
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
Represents an array with `unknown` value.
|
|
455
|
+
|
|
456
|
+
Use case: You want a type that all arrays can be assigned to, but you don't care about the value.
|
|
457
|
+
|
|
458
|
+
@example
|
|
459
|
+
```
|
|
460
|
+
import type {UnknownArray} from 'type-fest';
|
|
461
|
+
|
|
462
|
+
type IsArray<T> = T extends UnknownArray ? true : false;
|
|
463
|
+
|
|
464
|
+
type A = IsArray<['foo']>;
|
|
465
|
+
//=> true
|
|
466
|
+
|
|
467
|
+
type B = IsArray<readonly number[]>;
|
|
468
|
+
//=> true
|
|
469
|
+
|
|
470
|
+
type C = IsArray<string>;
|
|
471
|
+
//=> false
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
@category Type
|
|
475
|
+
@category Array
|
|
476
|
+
*/
|
|
477
|
+
type UnknownArray = readonly unknown[];
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
@see {@link SomeExtend}
|
|
481
|
+
*/
|
|
482
|
+
type SomeExtendOptions = {
|
|
483
|
+
/**
|
|
484
|
+
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
485
|
+
|
|
486
|
+
- 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`).
|
|
487
|
+
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
488
|
+
|
|
489
|
+
@default true
|
|
490
|
+
|
|
491
|
+
@example
|
|
492
|
+
```
|
|
493
|
+
import type {SomeExtend} from 'type-fest';
|
|
494
|
+
|
|
495
|
+
type A = SomeExtend<[1, 2, never], string, {strictNever: true}>;
|
|
496
|
+
//=> false
|
|
497
|
+
|
|
498
|
+
type B = SomeExtend<[1, 2, never], string, {strictNever: false}>;
|
|
499
|
+
//=> true
|
|
500
|
+
|
|
501
|
+
type C = SomeExtend<[1, never], never, {strictNever: true}>;
|
|
502
|
+
//=> true
|
|
503
|
+
|
|
504
|
+
type D = SomeExtend<[1, never], never, {strictNever: false}>;
|
|
505
|
+
//=> true
|
|
506
|
+
|
|
507
|
+
type E = SomeExtend<[never], any, {strictNever: true}>;
|
|
508
|
+
//=> true
|
|
509
|
+
|
|
510
|
+
type F = SomeExtend<[never], any, {strictNever: false}>;
|
|
511
|
+
//=> true
|
|
512
|
+
```
|
|
513
|
+
*/
|
|
514
|
+
strictNever?: boolean;
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
type DefaultSomeExtendOptions = {
|
|
518
|
+
strictNever: true;
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
Returns a boolean for whether some element in an array type extends another type.
|
|
523
|
+
|
|
524
|
+
Distributes over unions of arrays and element types, preserving uncertainty as `boolean` unless another element decides the result. Returns `false` when the array itself is `any` or `never`, whereas `SomeExtend<[any], number>` is `boolean`.
|
|
525
|
+
|
|
526
|
+
@example
|
|
527
|
+
```
|
|
528
|
+
import type {SomeExtend} from 'type-fest';
|
|
529
|
+
|
|
530
|
+
type A = SomeExtend<['1', '2', 3], number>;
|
|
531
|
+
//=> true
|
|
532
|
+
|
|
533
|
+
type B = SomeExtend<[1, 2, 3], string>;
|
|
534
|
+
//=> false
|
|
535
|
+
|
|
536
|
+
type C = SomeExtend<[string, number | string], number>;
|
|
537
|
+
//=> boolean
|
|
538
|
+
|
|
539
|
+
type D = SomeExtend<[true, boolean, true], false>;
|
|
540
|
+
//=> boolean
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
Note: Optional elements are checked by their declared types, without the implicit `undefined` from absence. This type supports `exactOptionalPropertyTypes: true`. An explicitly declared `undefined` remains part of the element type.
|
|
544
|
+
|
|
545
|
+
Known limitation: TypeScript infers an optional `never` element as `undefined`, so it is checked as `undefined`, regardless of `strictNever`.
|
|
546
|
+
|
|
547
|
+
```
|
|
548
|
+
// @exactOptionalPropertyTypes: true
|
|
549
|
+
import type {SomeExtend} from 'type-fest';
|
|
550
|
+
|
|
551
|
+
type A = SomeExtend<[1?, 2?, '3'?], string>;
|
|
552
|
+
//=> true
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
```
|
|
556
|
+
// @exactOptionalPropertyTypes: true
|
|
557
|
+
import type {SomeExtend} from 'type-fest';
|
|
558
|
+
|
|
559
|
+
type A = SomeExtend<['1'?, (2 | undefined)?], number>;
|
|
560
|
+
//=> boolean
|
|
561
|
+
|
|
562
|
+
type B = SomeExtend<['1'?, (2 | undefined)?], number | undefined>;
|
|
563
|
+
//=> true
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
@see {@link SomeExtendOptions}
|
|
567
|
+
|
|
568
|
+
@category Utilities
|
|
569
|
+
@category Array
|
|
570
|
+
*/
|
|
571
|
+
type SomeExtend<TArray extends UnknownArray, Type, Options extends SomeExtendOptions = {}> =
|
|
572
|
+
IfNotAnyOrNever<TArray, {
|
|
573
|
+
// Infer the underlying array separately from metadata so tuple inference preserves fixed positions.
|
|
574
|
+
ifNot: TArray extends (infer Array_ extends UnknownArray) & Pick<TArray, Exclude<keyof TArray, keyof unknown[] | `${number}`>>
|
|
575
|
+
? _SomeExtend<Array_, Type, ApplyDefaultOptions<SomeExtendOptions, DefaultSomeExtendOptions, Options>>
|
|
576
|
+
: never;
|
|
577
|
+
ifAny: false;
|
|
578
|
+
ifNever: false;
|
|
579
|
+
}>;
|
|
580
|
+
|
|
581
|
+
// Kept free of `IfNotAnyOrNever` so that it stays tail-recursive, which allows it to handle long arrays. An element that only partly matches makes the result a union with the rest of the search, which is not tail-recursive, so a long tuple of such elements can hit the instantiation depth limit.
|
|
582
|
+
type _SomeExtend<TArray extends UnknownArray, Type, Options extends Required<SomeExtendOptions>> =
|
|
583
|
+
'0' extends keyof TArray
|
|
584
|
+
? TArray extends readonly [(infer First)?, ...infer Rest]
|
|
585
|
+
? IsNever<First> extends true
|
|
586
|
+
? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true
|
|
587
|
+
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, return `true`.
|
|
588
|
+
? true
|
|
589
|
+
: _SomeExtend<Rest, Type, Options>
|
|
590
|
+
// Keep the original constraint so generic matches stay unresolved without widening known non-matches.
|
|
591
|
+
: (First extends Type ? true : false) extends infer Matches extends (First extends Type ? true : false)
|
|
592
|
+
? Matches extends true
|
|
593
|
+
? true
|
|
594
|
+
: _SomeExtend<Rest, Type, Options>
|
|
595
|
+
: never
|
|
596
|
+
: never // Should never happen, since the first fixed element can always be inferred.
|
|
597
|
+
: TArray extends readonly []
|
|
598
|
+
? false
|
|
599
|
+
// Collapse only an unconsumed rest element and its fixed suffix.
|
|
600
|
+
: _SomeExtend<CollapseRestElement<TArray>, Type, Options>;
|
|
601
|
+
|
|
602
|
+
// For `@link`
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
Returns a boolean for whether any of the given elements is `true`.
|
|
606
|
+
|
|
607
|
+
Use-cases:
|
|
608
|
+
- Check if at least one condition in a list of booleans is met.
|
|
609
|
+
|
|
610
|
+
Distributes over unions of arrays. Returns `false` when the entire input is `any` or `never`; non-boolean arrays are rejected.
|
|
611
|
+
|
|
612
|
+
@example
|
|
613
|
+
```
|
|
614
|
+
import type {OrAll} from 'type-fest';
|
|
615
|
+
|
|
616
|
+
type FFT = OrAll<[false, false, true]>;
|
|
617
|
+
//=> true
|
|
618
|
+
|
|
619
|
+
type FFF = OrAll<[false, false, false]>;
|
|
620
|
+
//=> false
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
Note: When `boolean` is passed as an element, it is distributed into separate cases, and the final result is a union of those cases.
|
|
624
|
+
For example, `OrAll<[false, boolean]>` expands to `OrAll<[false, true]> | OrAll<[false, false]>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
625
|
+
|
|
626
|
+
@example
|
|
627
|
+
```
|
|
628
|
+
import type {OrAll} from 'type-fest';
|
|
629
|
+
|
|
630
|
+
type A = OrAll<[false, boolean]>;
|
|
631
|
+
//=> boolean
|
|
632
|
+
|
|
633
|
+
type B = OrAll<[true, boolean]>;
|
|
634
|
+
//=> true
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
Note: If `never` is passed as an element, it is treated as `false` and the result is computed accordingly.
|
|
638
|
+
|
|
639
|
+
@example
|
|
640
|
+
```
|
|
641
|
+
import type {OrAll} from 'type-fest';
|
|
642
|
+
|
|
643
|
+
type A = OrAll<[never, never, true]>;
|
|
644
|
+
//=> true
|
|
645
|
+
|
|
646
|
+
type B = OrAll<[never, never, false]>;
|
|
647
|
+
//=> false
|
|
648
|
+
|
|
649
|
+
type C = OrAll<[never, never, never]>;
|
|
650
|
+
//=> false
|
|
651
|
+
|
|
652
|
+
type D = OrAll<[never, never, boolean]>;
|
|
653
|
+
//=> boolean
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
Note: If `any` is passed as an element, it is treated as `boolean` and the result is computed accordingly.
|
|
657
|
+
|
|
658
|
+
@example
|
|
659
|
+
```
|
|
660
|
+
import type {OrAll} from 'type-fest';
|
|
661
|
+
|
|
662
|
+
type A = OrAll<[false, any]>;
|
|
663
|
+
//=> boolean
|
|
664
|
+
|
|
665
|
+
type B = OrAll<[true, any]>;
|
|
666
|
+
//=> true
|
|
667
|
+
```
|
|
668
|
+
|
|
669
|
+
Note: `OrAll<[]>` evaluates to `false` because there are no `true` elements in an empty tuple. See [Wikipedia: Clause (logic) > Empty clauses](https://en.wikipedia.org/wiki/Clause_(logic)#Empty_clauses:~:text=The%20truth%20evaluation%20of%20an%20empty%20disjunctive%20clause%20is%20always%20false.).
|
|
670
|
+
|
|
671
|
+
@see {@link Or}
|
|
672
|
+
@see {@link AndAll}
|
|
673
|
+
*/
|
|
674
|
+
type OrAll<T extends readonly boolean[]> = SomeExtend<T, true>;
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
|
|
678
|
+
|
|
679
|
+
Use-cases:
|
|
680
|
+
- 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'>`.
|
|
681
|
+
|
|
682
|
+
Note:
|
|
683
|
+
- 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'`.
|
|
684
|
+
- Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
|
|
685
|
+
|
|
686
|
+
@example
|
|
687
|
+
```
|
|
688
|
+
import type {If} from 'type-fest';
|
|
689
|
+
|
|
690
|
+
type A = If<true, 'yes', 'no'>;
|
|
691
|
+
//=> 'yes'
|
|
692
|
+
|
|
693
|
+
type B = If<false, 'yes', 'no'>;
|
|
694
|
+
//=> 'no'
|
|
695
|
+
|
|
696
|
+
type C = If<boolean, 'yes', 'no'>;
|
|
697
|
+
//=> 'yes' | 'no'
|
|
698
|
+
|
|
699
|
+
type D = If<any, 'yes', 'no'>;
|
|
700
|
+
//=> 'yes' | 'no'
|
|
701
|
+
|
|
702
|
+
type E = If<never, 'yes', 'no'>;
|
|
703
|
+
//=> 'no'
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
@example
|
|
707
|
+
```
|
|
708
|
+
import type {If, IsAny, IsNever} from 'type-fest';
|
|
709
|
+
|
|
710
|
+
type A = If<IsAny<unknown>, 'is any', 'not any'>;
|
|
711
|
+
//=> 'not any'
|
|
712
|
+
|
|
713
|
+
type B = If<IsNever<never>, 'is never', 'not never'>;
|
|
714
|
+
//=> 'is never'
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
@example
|
|
718
|
+
```
|
|
719
|
+
import type {If, IsEqual} from 'type-fest';
|
|
720
|
+
|
|
721
|
+
type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
|
|
722
|
+
|
|
723
|
+
type A = IfEqual<string, string, 'equal', 'not equal'>;
|
|
724
|
+
//=> 'equal'
|
|
725
|
+
|
|
726
|
+
type B = IfEqual<string, number, 'equal', 'not equal'>;
|
|
727
|
+
//=> 'not equal'
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
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:
|
|
731
|
+
|
|
732
|
+
@example
|
|
733
|
+
```
|
|
734
|
+
import type {If, IsEqual, StringRepeat} from 'type-fest';
|
|
735
|
+
|
|
736
|
+
type HundredZeroes = StringRepeat<'0', 100>;
|
|
737
|
+
|
|
738
|
+
// The following implementation is not tail recursive
|
|
739
|
+
type Includes<S extends string, Char extends string> =
|
|
740
|
+
S extends `${infer First}${infer Rest}`
|
|
741
|
+
? If<IsEqual<First, Char>,
|
|
742
|
+
'found',
|
|
743
|
+
Includes<Rest, Char>>
|
|
744
|
+
: 'not found';
|
|
745
|
+
|
|
746
|
+
// Hence, instantiations with long strings will fail
|
|
747
|
+
// @ts-expect-error
|
|
748
|
+
type Fails = Includes<HundredZeroes, '1'>;
|
|
749
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
750
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
751
|
+
|
|
752
|
+
// However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
|
|
753
|
+
type IncludesWithoutIf<S extends string, Char extends string> =
|
|
754
|
+
S extends `${infer First}${infer Rest}`
|
|
755
|
+
? IsEqual<First, Char> extends true
|
|
756
|
+
? 'found'
|
|
757
|
+
: IncludesWithoutIf<Rest, Char>
|
|
758
|
+
: 'not found';
|
|
759
|
+
|
|
760
|
+
// Now, instantiations with long strings will work
|
|
761
|
+
type Works = IncludesWithoutIf<HundredZeroes, '1'>;
|
|
762
|
+
//=> 'not found'
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
@category Type Guard
|
|
766
|
+
@category Utilities
|
|
767
|
+
*/
|
|
768
|
+
type If<Type extends boolean, IfBranch, ElseBranch> =
|
|
769
|
+
IsNever<Type> extends true
|
|
770
|
+
? ElseBranch
|
|
771
|
+
: Type extends true
|
|
772
|
+
? IfBranch
|
|
773
|
+
: ElseBranch;
|
|
774
|
+
|
|
775
|
+
// For `@link`
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
Returns a boolean for whether either of two given types is `true`.
|
|
779
|
+
|
|
780
|
+
Use-case: Constructing complex conditional types where at least one condition must be satisfied.
|
|
781
|
+
|
|
782
|
+
An `any` operand is treated as `boolean`; non-boolean operands are rejected.
|
|
783
|
+
|
|
784
|
+
@example
|
|
785
|
+
```
|
|
786
|
+
import type {Or} from 'type-fest';
|
|
787
|
+
|
|
788
|
+
type TT = Or<true, true>;
|
|
789
|
+
//=> true
|
|
790
|
+
|
|
791
|
+
type TF = Or<true, false>;
|
|
792
|
+
//=> true
|
|
793
|
+
|
|
794
|
+
type FT = Or<false, true>;
|
|
795
|
+
//=> true
|
|
796
|
+
|
|
797
|
+
type FF = Or<false, false>;
|
|
798
|
+
//=> false
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
Note: When `boolean` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
|
|
802
|
+
For example, `Or<false, boolean>` expands to `Or<false, true> | Or<false, false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
803
|
+
|
|
804
|
+
@example
|
|
805
|
+
```
|
|
806
|
+
import type {Or} from 'type-fest';
|
|
807
|
+
|
|
808
|
+
type A = Or<false, boolean>;
|
|
809
|
+
//=> boolean
|
|
810
|
+
|
|
811
|
+
type B = Or<boolean, false>;
|
|
812
|
+
//=> boolean
|
|
813
|
+
|
|
814
|
+
type C = Or<true, boolean>;
|
|
815
|
+
//=> true
|
|
816
|
+
|
|
817
|
+
type D = Or<boolean, true>;
|
|
818
|
+
//=> true
|
|
819
|
+
|
|
820
|
+
type E = Or<boolean, boolean>;
|
|
821
|
+
//=> boolean
|
|
822
|
+
```
|
|
823
|
+
|
|
824
|
+
Note: If `never` is passed as an argument, it is treated as `false` and the result is computed accordingly.
|
|
825
|
+
|
|
826
|
+
@example
|
|
827
|
+
```
|
|
828
|
+
import type {Or} from 'type-fest';
|
|
829
|
+
|
|
830
|
+
type A = Or<true, never>;
|
|
831
|
+
//=> true
|
|
832
|
+
|
|
833
|
+
type B = Or<never, true>;
|
|
834
|
+
//=> true
|
|
835
|
+
|
|
836
|
+
type C = Or<false, never>;
|
|
837
|
+
//=> false
|
|
838
|
+
|
|
839
|
+
type D = Or<never, false>;
|
|
840
|
+
//=> false
|
|
841
|
+
|
|
842
|
+
type E = Or<boolean, never>;
|
|
843
|
+
//=> boolean
|
|
844
|
+
|
|
845
|
+
type F = Or<never, boolean>;
|
|
846
|
+
//=> boolean
|
|
847
|
+
|
|
848
|
+
type G = Or<never, never>;
|
|
849
|
+
//=> false
|
|
850
|
+
```
|
|
851
|
+
|
|
852
|
+
@see {@link OrAll}
|
|
853
|
+
@see {@link And}
|
|
854
|
+
@see {@link Xor}
|
|
855
|
+
*/
|
|
856
|
+
type Or<A extends boolean, B extends boolean> = OrAll<[A, B]>;
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
@see {@link AllExtend}
|
|
433
860
|
*/
|
|
434
|
-
type
|
|
861
|
+
type AllExtendOptions = {
|
|
862
|
+
/**
|
|
863
|
+
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
864
|
+
|
|
865
|
+
- 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`).
|
|
866
|
+
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
867
|
+
|
|
868
|
+
@default true
|
|
869
|
+
|
|
870
|
+
@example
|
|
871
|
+
```
|
|
872
|
+
import type {AllExtend} from 'type-fest';
|
|
873
|
+
|
|
874
|
+
type A = AllExtend<[1, 2, never], number, {strictNever: true}>;
|
|
875
|
+
//=> false
|
|
876
|
+
|
|
877
|
+
type B = AllExtend<[1, 2, never], number, {strictNever: false}>;
|
|
878
|
+
//=> true
|
|
879
|
+
|
|
880
|
+
type C = AllExtend<[never, never], never, {strictNever: true}>;
|
|
881
|
+
//=> true
|
|
882
|
+
|
|
883
|
+
type D = AllExtend<[never, never], never, {strictNever: false}>;
|
|
884
|
+
//=> true
|
|
885
|
+
|
|
886
|
+
type E = AllExtend<['a', 'b', never], any, {strictNever: true}>;
|
|
887
|
+
//=> true
|
|
888
|
+
|
|
889
|
+
type F = AllExtend<['a', 'b', never], any, {strictNever: false}>;
|
|
890
|
+
//=> true
|
|
891
|
+
|
|
892
|
+
type G = AllExtend<[never, 1], never, {strictNever: true}>;
|
|
893
|
+
//=> false
|
|
894
|
+
|
|
895
|
+
type H = AllExtend<[never, 1], never, {strictNever: false}>;
|
|
896
|
+
//=> false
|
|
897
|
+
```
|
|
898
|
+
*/
|
|
899
|
+
strictNever?: boolean;
|
|
900
|
+
};
|
|
901
|
+
|
|
902
|
+
type DefaultAllExtendOptions = {
|
|
903
|
+
strictNever: true;
|
|
904
|
+
};
|
|
435
905
|
|
|
436
906
|
/**
|
|
437
|
-
Returns a boolean for whether
|
|
907
|
+
Returns a boolean for whether every element in an array type extends another type.
|
|
908
|
+
|
|
909
|
+
Distributes over unions of arrays and element types, preserving uncertainty as `boolean` unless another element decides the result. Returns `false` when the array itself is `any` or `never`, whereas `AllExtend<[any], number>` is `boolean`.
|
|
438
910
|
|
|
439
911
|
@example
|
|
440
912
|
```
|
|
441
|
-
type
|
|
913
|
+
import type {AllExtend} from 'type-fest';
|
|
914
|
+
|
|
915
|
+
type A = AllExtend<[1, 2, 3], number>;
|
|
916
|
+
//=> true
|
|
917
|
+
|
|
918
|
+
type B = AllExtend<[1, 2, '3'], number>;
|
|
442
919
|
//=> false
|
|
443
920
|
|
|
444
|
-
type
|
|
921
|
+
type C = AllExtend<[number, number | string], number>;
|
|
922
|
+
//=> boolean
|
|
923
|
+
|
|
924
|
+
type D = AllExtend<[true, boolean, true], true>;
|
|
925
|
+
//=> boolean
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
Note: Optional elements are checked by their declared types, without the implicit `undefined` from absence. This type supports `exactOptionalPropertyTypes: true`. An explicitly declared `undefined` remains part of the element type.
|
|
929
|
+
|
|
930
|
+
Known limitation: TypeScript infers an optional `never` element as `undefined`, so it is checked as `undefined`, regardless of `strictNever`.
|
|
931
|
+
|
|
932
|
+
```
|
|
933
|
+
// @exactOptionalPropertyTypes: true
|
|
934
|
+
import type {AllExtend} from 'type-fest';
|
|
935
|
+
|
|
936
|
+
type A = AllExtend<[1?, 2?, 3?], number>;
|
|
937
|
+
//=> true
|
|
938
|
+
```
|
|
939
|
+
|
|
940
|
+
```
|
|
941
|
+
// @exactOptionalPropertyTypes: true
|
|
942
|
+
import type {AllExtend} from 'type-fest';
|
|
943
|
+
|
|
944
|
+
type A = AllExtend<[1?, (2 | undefined)?], number>;
|
|
945
|
+
//=> boolean
|
|
946
|
+
|
|
947
|
+
type B = AllExtend<[1?, (2 | undefined)?], number | undefined>;
|
|
445
948
|
//=> true
|
|
446
949
|
```
|
|
950
|
+
|
|
951
|
+
@see {@link AllExtendOptions}
|
|
952
|
+
|
|
953
|
+
@category Utilities
|
|
954
|
+
@category Array
|
|
447
955
|
*/
|
|
448
|
-
type
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
956
|
+
type AllExtend<TArray extends UnknownArray, Type, Options extends AllExtendOptions = {}> =
|
|
957
|
+
IfNotAnyOrNever<TArray, {
|
|
958
|
+
// Infer the underlying array separately from metadata so tuple inference preserves fixed positions.
|
|
959
|
+
ifNot: TArray extends (infer Array_ extends UnknownArray) & Pick<TArray, Exclude<keyof TArray, keyof unknown[] | `${number}`>>
|
|
960
|
+
? _AllExtend<Array_, Type, ApplyDefaultOptions<AllExtendOptions, DefaultAllExtendOptions, Options>>
|
|
961
|
+
: never;
|
|
962
|
+
ifAny: false;
|
|
963
|
+
ifNever: false;
|
|
964
|
+
}>;
|
|
965
|
+
|
|
966
|
+
// Kept free of `IfNotAnyOrNever` so that it stays tail-recursive, which allows it to handle long arrays. An element that only partly matches makes the result a union with the rest of the search, which is not tail-recursive, so a long tuple of such elements can hit the instantiation depth limit.
|
|
967
|
+
type _AllExtend<TArray extends UnknownArray, Type, Options extends Required<AllExtendOptions>> =
|
|
968
|
+
'0' extends keyof TArray
|
|
969
|
+
? TArray extends readonly [(infer First)?, ...infer Rest]
|
|
970
|
+
? IsNever<First> extends true
|
|
971
|
+
? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true
|
|
972
|
+
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, recurse further.
|
|
973
|
+
? _AllExtend<Rest, Type, Options>
|
|
974
|
+
: false
|
|
975
|
+
// Keep the original constraint so generic matches stay unresolved without widening known non-matches.
|
|
976
|
+
: (First extends Type ? true : false) extends infer Matches extends (First extends Type ? true : false)
|
|
977
|
+
? Matches extends true
|
|
978
|
+
? _AllExtend<Rest, Type, Options>
|
|
979
|
+
: false
|
|
980
|
+
: never
|
|
981
|
+
: never // Should never happen, since the first fixed element can always be inferred.
|
|
982
|
+
: TArray extends readonly []
|
|
983
|
+
? true
|
|
984
|
+
// Collapse only an unconsumed rest element and its fixed suffix.
|
|
985
|
+
: _AllExtend<CollapseRestElement<TArray>, Type, Options>;
|
|
986
|
+
|
|
987
|
+
// For `@link`
|
|
453
988
|
|
|
454
989
|
/**
|
|
455
|
-
|
|
990
|
+
Returns a boolean for whether the given type is `false`.
|
|
991
|
+
|
|
992
|
+
Use-case: Constructing complex conditional types where a condition must be negated.
|
|
456
993
|
|
|
457
994
|
@example
|
|
458
995
|
```
|
|
459
|
-
|
|
460
|
-
type A = IfNotAnyOrNever<string, 'VALID', 'IS_ANY', 'IS_NEVER'>;
|
|
461
|
-
//=> 'VALID'
|
|
996
|
+
import type {Not} from 'type-fest';
|
|
462
997
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
//=> 'IS_ANY'
|
|
998
|
+
type A = Not<true>;
|
|
999
|
+
//=> false
|
|
466
1000
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
//=> 'IS_NEVER'
|
|
1001
|
+
type B = Not<false>;
|
|
1002
|
+
//=> true
|
|
470
1003
|
```
|
|
471
1004
|
|
|
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
1005
|
@example
|
|
475
|
-
```
|
|
476
|
-
import type {
|
|
1006
|
+
```
|
|
1007
|
+
import type {IsAny, Not} from 'type-fest';
|
|
477
1008
|
|
|
478
|
-
type
|
|
1009
|
+
type IsNotAny<Value> = Not<IsAny<Value>>;
|
|
479
1010
|
|
|
480
|
-
|
|
481
|
-
|
|
1011
|
+
type A = IsNotAny<string>;
|
|
1012
|
+
//=> true
|
|
482
1013
|
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
487
|
-
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
1014
|
+
type B = IsNotAny<any>;
|
|
1015
|
+
//=> false
|
|
1016
|
+
```
|
|
488
1017
|
|
|
489
|
-
|
|
490
|
-
|
|
1018
|
+
Note: When `boolean` or `any` is passed as an argument, it is distributed into separate cases, and the final result is a union of those cases.
|
|
1019
|
+
For example, `Not<boolean>` expands to `Not<true> | Not<false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
491
1020
|
|
|
492
|
-
|
|
1021
|
+
@example
|
|
1022
|
+
```
|
|
1023
|
+
import type {Not} from 'type-fest';
|
|
493
1024
|
|
|
494
|
-
type
|
|
495
|
-
//=>
|
|
1025
|
+
type A = Not<boolean>;
|
|
1026
|
+
//=> boolean
|
|
1027
|
+
|
|
1028
|
+
type B = Not<any>;
|
|
1029
|
+
//=> boolean
|
|
496
1030
|
```
|
|
497
|
-
*/
|
|
498
|
-
type IfNotAnyOrNever<T, IfNotAnyOrNever, IfAny = any, IfNever = never> =
|
|
499
|
-
If<IsAny<T>, IfAny, If<IsNever<T>, IfNever, IfNotAnyOrNever>>;
|
|
500
1031
|
|
|
501
|
-
|
|
502
|
-
Indicates the value of `exactOptionalPropertyTypes` compiler option.
|
|
503
|
-
*/
|
|
504
|
-
type IsExactOptionalPropertyTypesEnabled = [(string | undefined)?] extends [string?]
|
|
505
|
-
? false
|
|
506
|
-
: true;
|
|
1032
|
+
Note: Like {@link And}, {@link Or}, and {@link Xor}, if `never` is passed as an argument, it is treated as `false` and the result is computed accordingly, so `Not<never>` is `true`.
|
|
507
1033
|
|
|
508
|
-
|
|
509
|
-
|
|
1034
|
+
@example
|
|
1035
|
+
```
|
|
1036
|
+
import type {Not} from 'type-fest';
|
|
1037
|
+
|
|
1038
|
+
type A = Not<never>;
|
|
1039
|
+
//=> true
|
|
1040
|
+
```
|
|
1041
|
+
|
|
1042
|
+
@see {@link If}
|
|
1043
|
+
@see {@link And}
|
|
1044
|
+
@see {@link Or}
|
|
1045
|
+
@see {@link Xor}
|
|
510
1046
|
*/
|
|
511
|
-
type
|
|
1047
|
+
type Not<A extends boolean> = If<A, false, true>;
|
|
512
1048
|
|
|
513
1049
|
/**
|
|
514
|
-
Transforms a tuple type by replacing
|
|
1050
|
+
Transforms a tuple type by replacing its rest element with a single element that has the same type as the rest element, while keeping all the non-rest elements intact.
|
|
515
1051
|
|
|
516
1052
|
@example
|
|
517
1053
|
```
|
|
@@ -528,20 +1064,20 @@ type D = CollapseRestElement<[string, number]>;
|
|
|
528
1064
|
//=> [string, number]
|
|
529
1065
|
```
|
|
530
1066
|
|
|
531
|
-
Note: Optional modifiers (`?`) are removed from elements
|
|
1067
|
+
Note: Optional modifiers (`?`) are removed from elements. Explicitly declared `undefined` is preserved.
|
|
532
1068
|
|
|
533
1069
|
@example
|
|
534
1070
|
```
|
|
535
|
-
//
|
|
1071
|
+
// Optional elements become required.
|
|
536
1072
|
type A = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
537
1073
|
//=> [string, string, number]
|
|
538
1074
|
|
|
539
|
-
// `
|
|
540
|
-
type B = CollapseRestElement<[string?, string?, ...number[]]>;
|
|
1075
|
+
// Explicitly declared `undefined` is preserved.
|
|
1076
|
+
type B = CollapseRestElement<[(string | undefined)?, (string | undefined)?, ...number[]]>;
|
|
541
1077
|
//=> [string | undefined, string | undefined, number]
|
|
542
1078
|
```
|
|
543
1079
|
*/
|
|
544
|
-
type CollapseRestElement<TArray extends UnknownArray> = IfNotAnyOrNever<TArray, _CollapseRestElement<TArray
|
|
1080
|
+
type CollapseRestElement<TArray extends UnknownArray> = IfNotAnyOrNever<TArray, {ifNot: _CollapseRestElement<TArray>}>;
|
|
545
1081
|
|
|
546
1082
|
type _CollapseRestElement<
|
|
547
1083
|
TArray extends UnknownArray,
|
|
@@ -549,36 +1085,57 @@ type _CollapseRestElement<
|
|
|
549
1085
|
BackwardAccumulator extends UnknownArray = [],
|
|
550
1086
|
> =
|
|
551
1087
|
TArray extends UnknownArray // For distributing `TArray`
|
|
552
|
-
? keyof TArray
|
|
553
|
-
// Enters this branch, if `TArray`
|
|
554
|
-
|
|
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]
|
|
1088
|
+
? '0' extends keyof TArray
|
|
1089
|
+
// Enters this branch, if `TArray` starts with a non-rest element (e.g., `[string, number]` or `[string, ...number[]]`).
|
|
1090
|
+
? TArray extends readonly [(infer First)?, ...infer Rest]
|
|
561
1091
|
? _CollapseRestElement<
|
|
562
1092
|
Rest,
|
|
563
1093
|
[
|
|
564
1094
|
...ForwardAccumulator,
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
: First,
|
|
1095
|
+
// Required and optional elements use the same inferred value, so no optional-position check is needed. Explicitly declared `undefined` is preserved.
|
|
1096
|
+
First,
|
|
568
1097
|
],
|
|
569
1098
|
BackwardAccumulator
|
|
570
1099
|
>
|
|
571
1100
|
: never // Should never happen, since `[(infer First)?, ...infer Rest]` is a top-type for arrays.
|
|
572
|
-
|
|
1101
|
+
// Enters this branch, if `TArray` is empty (e.g., []),
|
|
1102
|
+
// or `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
|
|
1103
|
+
: TArray extends readonly [...infer Rest, infer Last]
|
|
1104
|
+
? _CollapseRestElement<Rest, ForwardAccumulator, [Last, ...BackwardAccumulator]> // Accumulate elements that are present after the rest element.
|
|
1105
|
+
: TArray extends readonly []
|
|
1106
|
+
? [...ForwardAccumulator, ...BackwardAccumulator]
|
|
1107
|
+
: [...ForwardAccumulator, TArray[number], ...BackwardAccumulator] // Add the rest element between the accumulated elements.
|
|
1108
|
+
: never;
|
|
1109
|
+
|
|
1110
|
+
/**
|
|
1111
|
+
Matches a single whitespace character.
|
|
1112
|
+
|
|
1113
|
+
Uses the [ECMAScript trimming semantics](https://tc39.es/ecma262/multipage/text-processing.html#sec-trimstring): `WhiteSpace` plus `LineTerminator`, including line breaks and `U+FEFF` (BOM). Unlike Unicode's `White_Space` property, this excludes `U+0085` (NEXT LINE) and includes `U+FEFF`. It also excludes `U+180E` (MONGOLIAN VOWEL SEPARATOR) and `U+200B` (ZERO WIDTH SPACE).
|
|
1114
|
+
|
|
1115
|
+
Useful for type-level string parsing and separator validation. Matches exactly one character, not an empty string or a sequence of whitespace characters.
|
|
1116
|
+
|
|
1117
|
+
@example
|
|
1118
|
+
```
|
|
1119
|
+
import type {WhitespaceCharacter} from 'type-fest';
|
|
1120
|
+
|
|
1121
|
+
type Separator = Extract<' ' | '\t' | ',', WhitespaceCharacter>;
|
|
1122
|
+
//=> ' ' | '\t'
|
|
1123
|
+
|
|
1124
|
+
type Assignment = `${string}${WhitespaceCharacter}=${WhitespaceCharacter}${string}`;
|
|
1125
|
+
|
|
1126
|
+
const assignment: Assignment = 'size\t= large';
|
|
1127
|
+
```
|
|
573
1128
|
|
|
574
|
-
|
|
1129
|
+
@category String
|
|
1130
|
+
@category Template literal
|
|
1131
|
+
*/
|
|
1132
|
+
type WhitespaceCharacter =
|
|
575
1133
|
| '\u{9}' // '\t'
|
|
576
1134
|
| '\u{A}' // '\n'
|
|
577
1135
|
| '\u{B}' // '\v'
|
|
578
1136
|
| '\u{C}' // '\f'
|
|
579
1137
|
| '\u{D}' // '\r'
|
|
580
1138
|
| '\u{20}' // ' '
|
|
581
|
-
| '\u{85}'
|
|
582
1139
|
| '\u{A0}'
|
|
583
1140
|
| '\u{1680}'
|
|
584
1141
|
| '\u{2000}'
|
|
@@ -599,144 +1156,261 @@ type Whitespace =
|
|
|
599
1156
|
| '\u{3000}'
|
|
600
1157
|
| '\u{FEFF}';
|
|
601
1158
|
|
|
602
|
-
|
|
1159
|
+
// `U+0085` (next line) is not whitespace to `String.prototype.trim()`, but it still separates words.
|
|
1160
|
+
type WordSeparators = '-' | '_' | '\u{85}' | WhitespaceCharacter;
|
|
603
1161
|
|
|
604
1162
|
/**
|
|
605
|
-
|
|
1163
|
+
The characters of the Unicode titlecase category (`Lt`), which is closed at these 31 code points. Each is changed by both lowercasing and uppercasing, so a character like `Dž` is neither lowercase nor uppercase, though it also matches none of the uppercase or lowercase shapes the case predicates look for.
|
|
606
1164
|
*/
|
|
607
|
-
type
|
|
1165
|
+
type TitlecaseCharacter =
|
|
1166
|
+
| '\u{1C5}'
|
|
1167
|
+
| '\u{1C8}'
|
|
1168
|
+
| '\u{1CB}'
|
|
1169
|
+
| '\u{1F2}'
|
|
1170
|
+
| '\u{1F88}'
|
|
1171
|
+
| '\u{1F89}'
|
|
1172
|
+
| '\u{1F8A}'
|
|
1173
|
+
| '\u{1F8B}'
|
|
1174
|
+
| '\u{1F8C}'
|
|
1175
|
+
| '\u{1F8D}'
|
|
1176
|
+
| '\u{1F8E}'
|
|
1177
|
+
| '\u{1F8F}'
|
|
1178
|
+
| '\u{1F98}'
|
|
1179
|
+
| '\u{1F99}'
|
|
1180
|
+
| '\u{1F9A}'
|
|
1181
|
+
| '\u{1F9B}'
|
|
1182
|
+
| '\u{1F9C}'
|
|
1183
|
+
| '\u{1F9D}'
|
|
1184
|
+
| '\u{1F9E}'
|
|
1185
|
+
| '\u{1F9F}'
|
|
1186
|
+
| '\u{1FA8}'
|
|
1187
|
+
| '\u{1FA9}'
|
|
1188
|
+
| '\u{1FAA}'
|
|
1189
|
+
| '\u{1FAB}'
|
|
1190
|
+
| '\u{1FAC}'
|
|
1191
|
+
| '\u{1FAD}'
|
|
1192
|
+
| '\u{1FAE}'
|
|
1193
|
+
| '\u{1FAF}'
|
|
1194
|
+
| '\u{1FBC}'
|
|
1195
|
+
| '\u{1FCC}'
|
|
1196
|
+
| '\u{1FFC}';
|
|
608
1197
|
|
|
609
1198
|
/**
|
|
610
|
-
|
|
1199
|
+
Returns the canonical numeric spelling of the mapped `Key` when the selector `Keys` names it, or `never`.
|
|
1200
|
+
|
|
1201
|
+
A mapped type hands tuple elements over under their string form, so `'0'` must match a selector of `0`. Other numeric-looking names, such as `'01'`, stay distinct.
|
|
611
1202
|
*/
|
|
612
|
-
type
|
|
1203
|
+
type SelectedKeyAlias<Keys, Key> = MatchingKey<Record<Keys & PropertyKey, never>, Extract<Key, number | `${number}`>>;
|
|
613
1204
|
|
|
614
1205
|
/**
|
|
615
|
-
|
|
1206
|
+
Returns the keys of `Type` that the given `Keys` select.
|
|
1207
|
+
|
|
1208
|
+
A string enum member also selects the declared key with its value's name. A numeric enum member selects the declared key with its value, but not a `number` index signature. It is matched by its value, because `number` is assignable to a numeric enum.
|
|
616
1209
|
|
|
617
1210
|
@example
|
|
618
1211
|
```
|
|
619
|
-
|
|
1212
|
+
enum Index {
|
|
1213
|
+
Zero,
|
|
1214
|
+
One,
|
|
1215
|
+
}
|
|
620
1216
|
|
|
621
|
-
type
|
|
622
|
-
//=>
|
|
1217
|
+
type Keys = SelectedKeys<{[key: number]: string; 0: string; 1: string}, Index.One>;
|
|
1218
|
+
//=> 1
|
|
623
1219
|
```
|
|
1220
|
+
*/
|
|
1221
|
+
type SelectedKeys<Type, Keys> =
|
|
1222
|
+
| (KeySelector<Keys> & keyof Type)
|
|
1223
|
+
// A numeric enum key and its value do not intersect, so declared numeric keys are also matched by their value. The values are compared instead of the enum members, because `number` is assignable to a numeric enum.
|
|
1224
|
+
// The `keyof Type` filter is on the `Type` side, because nesting it around the `Keys` side makes type-checking run out of memory when `Keys` is an unresolved generic.
|
|
1225
|
+
| Extract<KeySelector<Keys>, Extract<KeySelector<keyof Type & number>, keyof Type>>;
|
|
624
1226
|
|
|
625
|
-
|
|
626
|
-
|
|
1227
|
+
/**
|
|
1228
|
+
Replaces a numeric enum member with its value, and adds the value's name of a string enum member.
|
|
1229
|
+
*/
|
|
1230
|
+
type KeySelector<Key> =
|
|
1231
|
+
Key extends unknown // To distribute `Key`
|
|
1232
|
+
// A wide key, such as `number` or `string & {}`, is kept as is.
|
|
1233
|
+
? {} extends Record<Key & PropertyKey, never>
|
|
1234
|
+
? Key
|
|
1235
|
+
: Key extends number
|
|
1236
|
+
? `${Key}` extends `${infer Value extends number}` ? Value : Key
|
|
1237
|
+
: Key | KeyToString<Key & string>
|
|
1238
|
+
: never;
|
|
1239
|
+
|
|
1240
|
+
// For `@link`
|
|
1241
|
+
|
|
1242
|
+
/**
|
|
1243
|
+
Returns a boolean for whether the given array or tuple is readonly.
|
|
1244
|
+
|
|
1245
|
+
Useful for writing array transformations that preserve mutability. Only the outer array is checked, not its elements.
|
|
1246
|
+
|
|
1247
|
+
Distributes over unions: A mix of mutable and readonly arrays returns `boolean`. Returns `boolean` for `any` and `false` for `never`. Non-array types are not accepted.
|
|
1248
|
+
|
|
1249
|
+
@example
|
|
1250
|
+
```
|
|
1251
|
+
import type {IsReadonlyArray} from 'type-fest';
|
|
1252
|
+
|
|
1253
|
+
type Readonly = IsReadonlyArray<readonly string[]>;
|
|
1254
|
+
//=> true
|
|
1255
|
+
|
|
1256
|
+
type Mutable = IsReadonlyArray<[string, number?]>;
|
|
1257
|
+
//=> false
|
|
1258
|
+
|
|
1259
|
+
type Mixed = IsReadonlyArray<string[] | readonly number[]>;
|
|
1260
|
+
//=> boolean
|
|
1261
|
+
```
|
|
1262
|
+
|
|
1263
|
+
@example
|
|
1264
|
+
```
|
|
1265
|
+
import type {If, IsReadonlyArray} from 'type-fest';
|
|
1266
|
+
|
|
1267
|
+
type WrapElements<Array_ extends readonly unknown[]> = Array_ extends unknown
|
|
1268
|
+
? If<IsReadonlyArray<Array_>, ReadonlyArray<{value: Array_[number]}>, Array<{value: Array_[number]}>>
|
|
1269
|
+
: never;
|
|
1270
|
+
|
|
1271
|
+
type Mutable = WrapElements<string[]>;
|
|
1272
|
+
//=> {value: string}[]
|
|
1273
|
+
|
|
1274
|
+
type Readonly = WrapElements<readonly number[]>;
|
|
1275
|
+
//=> readonly {value: number}[]
|
|
1276
|
+
|
|
1277
|
+
type Mixed = WrapElements<string[] | readonly number[]>;
|
|
1278
|
+
//=> {value: string}[] | readonly {value: number}[]
|
|
1279
|
+
```
|
|
1280
|
+
|
|
1281
|
+
This checks assignability to mutable arrays. Custom array types without the full mutable array interface, such as {@link FixedLengthArray}, are treated as readonly even if individual indices are writable. The `never` check prevents an empty union from returning `never`.
|
|
1282
|
+
|
|
1283
|
+
@category Type Guard
|
|
1284
|
+
@category Array
|
|
627
1285
|
*/
|
|
628
|
-
type
|
|
1286
|
+
type IsReadonlyArray<Array_ extends UnknownArray> = IsNever<Array_> extends true ? false : Array_ extends unknown[] ? false : true;
|
|
629
1287
|
|
|
630
1288
|
/**
|
|
631
|
-
|
|
1289
|
+
Represents a map with `unknown` key and value.
|
|
1290
|
+
|
|
1291
|
+
Use case: You want a type that all maps can be assigned to, but you don't care about the value.
|
|
1292
|
+
|
|
1293
|
+
@example
|
|
1294
|
+
```
|
|
1295
|
+
import type {UnknownMap} from 'type-fest';
|
|
1296
|
+
|
|
1297
|
+
type IsMap<T> = T extends UnknownMap ? true : false;
|
|
1298
|
+
|
|
1299
|
+
type A = IsMap<Map<string, number>>;
|
|
1300
|
+
//=> true
|
|
1301
|
+
|
|
1302
|
+
type B = IsMap<ReadonlyMap<number, string>>;
|
|
1303
|
+
//=> true
|
|
1304
|
+
|
|
1305
|
+
type C = IsMap<string>;
|
|
1306
|
+
//=> false
|
|
1307
|
+
```
|
|
632
1308
|
|
|
633
|
-
|
|
1309
|
+
@category Type
|
|
634
1310
|
*/
|
|
635
|
-
type
|
|
636
|
-
? Trim<T> extends T
|
|
637
|
-
? true
|
|
638
|
-
: false
|
|
639
|
-
: false;
|
|
1311
|
+
type UnknownMap = ReadonlyMap<unknown, unknown>;
|
|
640
1312
|
|
|
641
1313
|
/**
|
|
642
|
-
|
|
1314
|
+
Represents a set with `unknown` value.
|
|
1315
|
+
|
|
1316
|
+
Use case: You want a type that all sets can be assigned to, but you don't care about the value.
|
|
643
1317
|
|
|
644
1318
|
@example
|
|
645
1319
|
```
|
|
646
|
-
import type {
|
|
1320
|
+
import type {UnknownSet} from 'type-fest';
|
|
647
1321
|
|
|
648
|
-
type
|
|
649
|
-
top: number;
|
|
650
|
-
left: number;
|
|
651
|
-
};
|
|
1322
|
+
type IsSet<T> = T extends UnknownSet ? true : false;
|
|
652
1323
|
|
|
653
|
-
type
|
|
654
|
-
|
|
655
|
-
height: number;
|
|
656
|
-
};
|
|
1324
|
+
type A = IsSet<Set<string>>;
|
|
1325
|
+
//=> true
|
|
657
1326
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
```
|
|
1327
|
+
type B = IsSet<ReadonlySet<number>>;
|
|
1328
|
+
//=> true
|
|
661
1329
|
|
|
662
|
-
|
|
1330
|
+
type C = IsSet<string>;
|
|
1331
|
+
//=> false
|
|
1332
|
+
```
|
|
663
1333
|
|
|
664
|
-
|
|
1334
|
+
@category Type
|
|
1335
|
+
*/
|
|
1336
|
+
type UnknownSet = ReadonlySet<unknown>;
|
|
665
1337
|
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
import type {Simplify} from 'type-fest';
|
|
1338
|
+
/**
|
|
1339
|
+
Matches an array, map, or set, including readonly and weak variants.
|
|
669
1340
|
|
|
670
|
-
|
|
671
|
-
foo: number;
|
|
672
|
-
bar?: string;
|
|
673
|
-
baz: number | undefined;
|
|
674
|
-
}
|
|
1341
|
+
Use as a constraint or to select collection members from a union without specifying their element, key, or value types. Tuples are included.
|
|
675
1342
|
|
|
676
|
-
type
|
|
677
|
-
foo: number;
|
|
678
|
-
bar?: string;
|
|
679
|
-
baz: number | undefined;
|
|
680
|
-
};
|
|
1343
|
+
Matching is structural, so custom types with a compatible collection interface are included. Typed arrays and types that are only array-like or iterable are not included. Weak collections are included, so this type does not guarantee iteration or a `size` property.
|
|
681
1344
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
1345
|
+
@example
|
|
1346
|
+
```
|
|
1347
|
+
import type {UnknownCollection} from 'type-fest';
|
|
685
1348
|
|
|
686
|
-
|
|
1349
|
+
type CacheValue = string[] | Map<string, number> | WeakSet<object> | {updatedAt: Date};
|
|
687
1350
|
|
|
688
|
-
|
|
689
|
-
|
|
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`
|
|
1351
|
+
type Collections = Extract<CacheValue, UnknownCollection>;
|
|
1352
|
+
//=> string[] | Map<string, number> | WeakSet<object>
|
|
693
1353
|
```
|
|
694
1354
|
|
|
695
|
-
@
|
|
696
|
-
@
|
|
697
|
-
@category Object
|
|
1355
|
+
@category Type
|
|
1356
|
+
@category Array
|
|
698
1357
|
*/
|
|
699
|
-
type
|
|
1358
|
+
type UnknownCollection = UnknownArray | UnknownMap | UnknownSet | WeakMap<WeakKey, unknown> | WeakSet<WeakKey>;
|
|
700
1359
|
|
|
701
|
-
|
|
702
|
-
Returns a boolean for whether the two given types are equal.
|
|
1360
|
+
// For `@link`
|
|
703
1361
|
|
|
704
|
-
|
|
705
|
-
|
|
1362
|
+
/**
|
|
1363
|
+
Pick only index signatures from the given object type, leaving out all explicitly defined properties.
|
|
706
1364
|
|
|
707
|
-
|
|
708
|
-
- If you want to make a conditional branch based on the result of a comparison of two types.
|
|
1365
|
+
This is the counterpart of `OmitIndexSignature`.
|
|
709
1366
|
|
|
710
1367
|
@example
|
|
711
1368
|
```
|
|
712
|
-
import type {
|
|
1369
|
+
import type {PickIndexSignature} from 'type-fest';
|
|
713
1370
|
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
type
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
1371
|
+
declare const symbolKey: unique symbol;
|
|
1372
|
+
|
|
1373
|
+
type Example = {
|
|
1374
|
+
// These index signatures will remain.
|
|
1375
|
+
[x: string]: unknown;
|
|
1376
|
+
[x: number]: unknown;
|
|
1377
|
+
[x: symbol]: unknown;
|
|
1378
|
+
[x: `head-${string}`]: string;
|
|
1379
|
+
[x: `${string}-tail`]: string;
|
|
1380
|
+
[x: `head-${string}-tail`]: string;
|
|
1381
|
+
[x: `${bigint}`]: string;
|
|
1382
|
+
[x: `embedded-${number}`]: string;
|
|
1383
|
+
|
|
1384
|
+
// These explicitly defined keys will be removed.
|
|
1385
|
+
['kebab-case-key']: string;
|
|
1386
|
+
[symbolKey]: string;
|
|
1387
|
+
foo: 'bar';
|
|
1388
|
+
qux?: 'baz';
|
|
1389
|
+
};
|
|
1390
|
+
|
|
1391
|
+
type ExampleIndexSignature = PickIndexSignature<Example>;
|
|
1392
|
+
// {
|
|
1393
|
+
// [x: string]: unknown;
|
|
1394
|
+
// [x: number]: unknown;
|
|
1395
|
+
// [x: symbol]: unknown;
|
|
1396
|
+
// [x: `head-${string}`]: string;
|
|
1397
|
+
// [x: `${string}-tail`]: string;
|
|
1398
|
+
// [x: `head-${string}-tail`]: string;
|
|
1399
|
+
// [x: `${bigint}`]: string;
|
|
1400
|
+
// [x: `embedded-${number}`]: string;
|
|
1401
|
+
// }
|
|
722
1402
|
```
|
|
723
1403
|
|
|
724
|
-
@
|
|
725
|
-
@category
|
|
1404
|
+
@see {@link OmitIndexSignature}
|
|
1405
|
+
@category Object
|
|
726
1406
|
*/
|
|
727
|
-
type
|
|
728
|
-
[
|
|
729
|
-
?
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
: false;
|
|
1407
|
+
type PickIndexSignature<ObjectType> = {
|
|
1408
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, never>
|
|
1409
|
+
? KeyType
|
|
1410
|
+
: never]: ObjectType[KeyType];
|
|
1411
|
+
};
|
|
733
1412
|
|
|
734
|
-
//
|
|
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;
|
|
1413
|
+
// For `@link`
|
|
740
1414
|
|
|
741
1415
|
/**
|
|
742
1416
|
Omit any index signatures from the given object type, leaving only explicitly defined properties.
|
|
@@ -748,34 +1422,34 @@ Use-cases:
|
|
|
748
1422
|
|
|
749
1423
|
This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
750
1424
|
|
|
751
|
-
It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string,
|
|
1425
|
+
It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, never>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', never>`.
|
|
752
1426
|
|
|
753
|
-
|
|
1427
|
+
The `never` value type prevents inherited `Object.prototype` members, such as `toString`, from satisfying an explicitly defined key.
|
|
754
1428
|
|
|
755
1429
|
```
|
|
756
|
-
const indexed: Record<string,
|
|
1430
|
+
const indexed: Record<string, never> = {}; // Allowed
|
|
757
1431
|
|
|
758
1432
|
// @ts-expect-error
|
|
759
|
-
const keyed: Record<'foo',
|
|
760
|
-
// TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar",
|
|
1433
|
+
const keyed: Record<'foo' | 'bar', never> = {}; // Error
|
|
1434
|
+
// TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", never>': foo, bar
|
|
761
1435
|
```
|
|
762
1436
|
|
|
763
1437
|
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
1438
|
|
|
765
1439
|
```
|
|
766
|
-
type Indexed = {} extends Record<string,
|
|
767
|
-
? '✅ `{}` is assignable to `Record<string,
|
|
768
|
-
: '❌ `{}` is NOT assignable to `Record<string,
|
|
1440
|
+
type Indexed = {} extends Record<string, never>
|
|
1441
|
+
? '✅ `{}` is assignable to `Record<string, never>`'
|
|
1442
|
+
: '❌ `{}` is NOT assignable to `Record<string, never>`';
|
|
769
1443
|
|
|
770
1444
|
type IndexedResult = Indexed;
|
|
771
|
-
//=> '✅ `{}` is assignable to `Record<string,
|
|
1445
|
+
//=> '✅ `{}` is assignable to `Record<string, never>`'
|
|
772
1446
|
|
|
773
|
-
type Keyed = {} extends Record<'foo' | 'bar',
|
|
774
|
-
? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\',
|
|
775
|
-
: '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\',
|
|
1447
|
+
type Keyed = {} extends Record<'foo' | 'bar', never>
|
|
1448
|
+
? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', never>`'
|
|
1449
|
+
: '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', never>`';
|
|
776
1450
|
|
|
777
1451
|
type KeyedResult = Keyed;
|
|
778
|
-
//=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\',
|
|
1452
|
+
//=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', never>`'
|
|
779
1453
|
```
|
|
780
1454
|
|
|
781
1455
|
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`...
|
|
@@ -787,15 +1461,15 @@ type OmitIndexSignature<ObjectType> = {
|
|
|
787
1461
|
};
|
|
788
1462
|
```
|
|
789
1463
|
|
|
790
|
-
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType,
|
|
1464
|
+
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, never>`)...
|
|
791
1465
|
|
|
792
1466
|
```
|
|
793
1467
|
type OmitIndexSignature<ObjectType> = {
|
|
794
1468
|
[KeyType in keyof ObjectType
|
|
795
|
-
// Is `{}` assignable to `Record<KeyType,
|
|
796
|
-
as {} extends Record<KeyType,
|
|
797
|
-
? never // ✅ `{}` is assignable to `Record<KeyType,
|
|
798
|
-
: KeyType // ❌ `{}` is NOT assignable to `Record<KeyType,
|
|
1469
|
+
// Is `{}` assignable to `Record<KeyType, never>`?
|
|
1470
|
+
as {} extends Record<KeyType, never>
|
|
1471
|
+
? never // ✅ `{}` is assignable to `Record<KeyType, never>`
|
|
1472
|
+
: KeyType // ❌ `{}` is NOT assignable to `Record<KeyType, never>`
|
|
799
1473
|
]: ObjectType[KeyType];
|
|
800
1474
|
};
|
|
801
1475
|
```
|
|
@@ -817,773 +1491,1182 @@ type Example = {
|
|
|
817
1491
|
[x: `${bigint}`]: string;
|
|
818
1492
|
[x: `embedded-${number}`]: string;
|
|
819
1493
|
|
|
820
|
-
// These explicitly defined keys will remain.
|
|
821
|
-
foo: 'bar';
|
|
822
|
-
qux?: 'baz';
|
|
823
|
-
};
|
|
1494
|
+
// These explicitly defined keys will remain.
|
|
1495
|
+
foo: 'bar';
|
|
1496
|
+
qux?: 'baz';
|
|
1497
|
+
};
|
|
1498
|
+
|
|
1499
|
+
type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
|
|
1500
|
+
//=> {foo: 'bar'; qux?: 'baz'}
|
|
1501
|
+
```
|
|
1502
|
+
|
|
1503
|
+
@see {@link PickIndexSignature}
|
|
1504
|
+
@category Object
|
|
1505
|
+
*/
|
|
1506
|
+
type OmitIndexSignature<ObjectType> = {
|
|
1507
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, never>
|
|
1508
|
+
? never
|
|
1509
|
+
: KeyType]: ObjectType[KeyType];
|
|
1510
|
+
};
|
|
1511
|
+
|
|
1512
|
+
// For `@link`
|
|
1513
|
+
|
|
1514
|
+
/**
|
|
1515
|
+
Matches a `Date` that cannot be changed.
|
|
1516
|
+
|
|
1517
|
+
Use-cases:
|
|
1518
|
+
- Type a parameter of a function that only reads a date, so the function cannot change it. The [`prefer-readonly-parameter-types`](https://typescript-eslint.io/rules/prefer-readonly-parameter-types/) lint rule flags a `Date` parameter, but accepts a `ReadonlyDate`.
|
|
1519
|
+
- Type the return value of a function that hands out a date the caller must not change.
|
|
1520
|
+
|
|
1521
|
+
@example
|
|
1522
|
+
```
|
|
1523
|
+
import type {ReadonlyDate} from 'type-fest';
|
|
1524
|
+
|
|
1525
|
+
function formatDate(date: ReadonlyDate): string {
|
|
1526
|
+
return date.toISOString().slice(0, 10);
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
declare const date: Date;
|
|
1530
|
+
formatDate(date);
|
|
1531
|
+
//=> string
|
|
1532
|
+
|
|
1533
|
+
declare const readonlyDate: ReadonlyDate;
|
|
1534
|
+
formatDate(readonlyDate);
|
|
1535
|
+
|
|
1536
|
+
// @ts-expect-error -- Property 'setTime' does not exist on type 'ReadonlyDate'.
|
|
1537
|
+
readonlyDate.setTime(0);
|
|
1538
|
+
|
|
1539
|
+
// Get a mutable copy when you need one.
|
|
1540
|
+
// eslint-disable-next-line unicorn/consistent-date-clone -- A `ReadonlyDate` cannot be passed to `new Date()`.
|
|
1541
|
+
const mutableDate = new Date(readonlyDate.getTime());
|
|
1542
|
+
//=> Date
|
|
1543
|
+
```
|
|
1544
|
+
|
|
1545
|
+
Note: A `Date` is assignable to a `ReadonlyDate`, but a `ReadonlyDate` is not assignable to a `Date`, like `ReadonlyArray` and `Array`. Code that hands a `ReadonlyDate` to a function that takes a `Date`, like most date libraries, needs `new Date(readonlyDate.getTime())`.
|
|
1546
|
+
|
|
1547
|
+
Note: This is only a compile-time check. The value is still a `Date` at runtime, so plain JavaScript can still change it, and `Object.freeze()` does not stop the setters. An `instanceof Date` check narrows the type back to `Date`, which brings the setters back. Use [`Temporal`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal) for values that cannot be changed at runtime.
|
|
1548
|
+
|
|
1549
|
+
Note: It removes every `set*` method, including a setter that a project adds to `Date`.
|
|
1550
|
+
|
|
1551
|
+
{@link ReadonlyDeep `ReadonlyDeep`} turns a `Date` into a `ReadonlyDate`, and {@link WritableDeep `WritableDeep`} turns a `ReadonlyDate` back into a `Date`. The other `*Deep` types do not walk into a `ReadonlyDate`.
|
|
1552
|
+
|
|
1553
|
+
@category Object
|
|
1554
|
+
*/
|
|
1555
|
+
type ReadonlyDate = {
|
|
1556
|
+
readonly [Key in keyof Date as Key extends `set${string}` ? never : Key]: Date[Key];
|
|
1557
|
+
};
|
|
1558
|
+
|
|
1559
|
+
/**
|
|
1560
|
+
Matches any primitive, `void`, `Date`, or `RegExp` value.
|
|
1561
|
+
*/
|
|
1562
|
+
type BuiltIns = Primitive | void | Date | RegExp;
|
|
1563
|
+
|
|
1564
|
+
/**
|
|
1565
|
+
Matches the built-ins that are a single value rather than a structure to recurse into. Recursing into any of them replaces their members with something useless, so the `*Deep` types keep them as is. The exceptions are `ReadonlyDeep`, which turns a `Date` into a `ReadonlyDate`, and `WritableDeep`, which turns a `ReadonlyDate` back into a `Date`.
|
|
1566
|
+
|
|
1567
|
+
A plain construct signature is assignable to an abstract one, so the abstract form matches every class constructor.
|
|
1568
|
+
*/
|
|
1569
|
+
type NonRecursiveLeaf =
|
|
1570
|
+
| BuiltIns
|
|
1571
|
+
// A `ReadonlyDate` is not a `Date`, so `BuiltIns` does not match it, and recursing into it replaces its methods with something useless.
|
|
1572
|
+
| ReadonlyDate
|
|
1573
|
+
| (abstract new (...arguments_: any[]) => unknown)
|
|
1574
|
+
| ArrayBuffer
|
|
1575
|
+
| SharedArrayBuffer
|
|
1576
|
+
| DataView
|
|
1577
|
+
| TypedArray
|
|
1578
|
+
// A DOM node, like `HTMLElement` or `Document`. Recursing into it walks the whole DOM. Looked up through `globalThis` so that a `lib` without `DOM` gets `never` here instead of a compile error.
|
|
1579
|
+
| FindGlobalInstanceType<'Node'>;
|
|
1580
|
+
|
|
1581
|
+
/**
|
|
1582
|
+
Matches non-recursive types: {@link NonRecursiveLeaf} plus thenables (`PromiseLike`), which `await` unwraps rather than walks, and functions.
|
|
1583
|
+
*/
|
|
1584
|
+
type NonRecursiveType = NonRecursiveLeaf | PromiseLike<unknown> | Function;
|
|
1585
|
+
|
|
1586
|
+
/**
|
|
1587
|
+
An if-else-like type that resolves depending on whether the given type is `any` or `never`.
|
|
1588
|
+
|
|
1589
|
+
@example
|
|
1590
|
+
```
|
|
1591
|
+
// When `T` is neither `any` nor `never` (like `string`) => Returns the `ifNot` branch
|
|
1592
|
+
type A = IfNotAnyOrNever<string, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
1593
|
+
//=> 'VALID'
|
|
1594
|
+
|
|
1595
|
+
// When `T` is `any` => Returns the `ifAny` branch
|
|
1596
|
+
type B = IfNotAnyOrNever<any, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
1597
|
+
//=> 'IS_ANY'
|
|
1598
|
+
|
|
1599
|
+
// When `T` is `never` => Returns the `ifNever` branch
|
|
1600
|
+
type C = IfNotAnyOrNever<never, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
|
|
1601
|
+
//=> 'IS_NEVER'
|
|
1602
|
+
```
|
|
1603
|
+
|
|
1604
|
+
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:
|
|
1605
|
+
|
|
1606
|
+
@example
|
|
1607
|
+
```ts
|
|
1608
|
+
import type {StringRepeat} from 'type-fest';
|
|
1609
|
+
|
|
1610
|
+
type NineHundredNinetyNineSpaces = StringRepeat<' ', 999>;
|
|
1611
|
+
|
|
1612
|
+
// The following implementation is not tail recursive
|
|
1613
|
+
type TrimLeft<S extends string> = IfNotAnyOrNever<S, {ifNot: S extends ` ${infer R}` ? TrimLeft<R> : S}>;
|
|
1614
|
+
|
|
1615
|
+
// Hence, instantiations with long strings will fail
|
|
1616
|
+
// @ts-expect-error
|
|
1617
|
+
type T1 = TrimLeft<NineHundredNinetyNineSpaces>;
|
|
1618
|
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
1619
|
+
// Error: Type instantiation is excessively deep and possibly infinite.
|
|
1620
|
+
|
|
1621
|
+
// To fix this, move the recursion into a helper type
|
|
1622
|
+
type TrimLeftOptimised<S extends string> = IfNotAnyOrNever<S, {ifNot: _TrimLeftOptimised<S>}>;
|
|
1623
|
+
|
|
1624
|
+
type _TrimLeftOptimised<S extends string> = S extends ` ${infer R}` ? _TrimLeftOptimised<R> : S;
|
|
1625
|
+
|
|
1626
|
+
type T2 = TrimLeftOptimised<NineHundredNinetyNineSpaces>;
|
|
1627
|
+
//=> ''
|
|
1628
|
+
```
|
|
1629
|
+
*/
|
|
1630
|
+
type IfNotAnyOrNever<T, Cases extends {ifNot: unknown; ifAny?: unknown; ifNever?: unknown}> =
|
|
1631
|
+
IsAny<T> extends true
|
|
1632
|
+
? 'ifAny' extends keyof Cases
|
|
1633
|
+
? Cases['ifAny']
|
|
1634
|
+
: any
|
|
1635
|
+
: IsNever<T> extends true
|
|
1636
|
+
? 'ifNever' extends keyof Cases
|
|
1637
|
+
? Cases['ifNever']
|
|
1638
|
+
: never
|
|
1639
|
+
: Cases['ifNot'];
|
|
1640
|
+
|
|
1641
|
+
/**
|
|
1642
|
+
The call signature of the given type, rebuilt with its `this` parameter, which `Parameters` leaves out, so the rebuilt signature does not accept any receiver. A function that declares no `this` is rebuilt without one, like `OmitThisParameter` does, because `this: unknown` would reject a function that declares a `this`. `unknown` for a type that is not callable, so it can be intersected with anything.
|
|
1643
|
+
|
|
1644
|
+
Readonly rest parameters are preserved.
|
|
1645
|
+
|
|
1646
|
+
Note: An overloaded function keeps only its last signature, and a generic one loses its type parameters.
|
|
1647
|
+
*/
|
|
1648
|
+
type CallSignatureOf<Type> = Type extends (this: infer Receiver, ...arguments_: infer Arguments extends UnknownArray) => infer Return
|
|
1649
|
+
? unknown extends Receiver
|
|
1650
|
+
? (...arguments_: Arguments) => Return
|
|
1651
|
+
: (this: Receiver, ...arguments_: Arguments) => Return
|
|
1652
|
+
: unknown;
|
|
1653
|
+
|
|
1654
|
+
// `Opaque` and `Tagged` are for `@link`.
|
|
1655
|
+
|
|
1656
|
+
/**
|
|
1657
|
+
Remove brand properties from primitive types while preserving literal types.
|
|
1658
|
+
|
|
1659
|
+
Useful for recovering literal keys from branded types. Unlike {@link LiteralToPrimitive}, this does not widen literals. This distributes over unions. Non-primitive members are returned unchanged, including their brands and nested properties. `any`, `never`, and `unknown` are also returned unchanged.
|
|
1660
|
+
|
|
1661
|
+
@example
|
|
1662
|
+
```
|
|
1663
|
+
import type {Tagged, UnwrapBrandedPrimitive} from 'type-fest';
|
|
1664
|
+
|
|
1665
|
+
type Status = ('draft' | 'published') & {readonly __brand: 'Status'};
|
|
1666
|
+
|
|
1667
|
+
type StatusName = UnwrapBrandedPrimitive<Status>;
|
|
1668
|
+
//=> 'draft' | 'published'
|
|
1669
|
+
|
|
1670
|
+
type StatusCounts = Record<UnwrapBrandedPrimitive<Status>, number>;
|
|
1671
|
+
//=> {draft: number; published: number}
|
|
1672
|
+
|
|
1673
|
+
type UserId = UnwrapBrandedPrimitive<Tagged<string, 'UserId'>>;
|
|
1674
|
+
//=> string
|
|
1675
|
+
```
|
|
1676
|
+
|
|
1677
|
+
@example
|
|
1678
|
+
```
|
|
1679
|
+
import type {UnwrapBrandedPrimitive} from 'type-fest';
|
|
1680
|
+
|
|
1681
|
+
type Brand = {readonly __brand: unique symbol};
|
|
1682
|
+
|
|
1683
|
+
type A = UnwrapBrandedPrimitive<string & Brand>;
|
|
1684
|
+
//=> string
|
|
1685
|
+
|
|
1686
|
+
type B = UnwrapBrandedPrimitive<number & Brand>;
|
|
1687
|
+
//=> number
|
|
1688
|
+
|
|
1689
|
+
type C = UnwrapBrandedPrimitive<PropertyKey & Brand>;
|
|
1690
|
+
//=> number | string | symbol
|
|
1691
|
+
|
|
1692
|
+
type D = UnwrapBrandedPrimitive<(1 | 200n | 'foo' | 'bar') & Brand>;
|
|
1693
|
+
//=> 1 | 200n | 'foo' | 'bar'
|
|
1694
|
+
```
|
|
1695
|
+
|
|
1696
|
+
Custom brands must use a single object with explicit marker properties, such as `string & {brand: 'Id'}`. Optional markers, including a single {@link Flavor}, are supported. Separate custom intersections, such as `string & BrandA & BrandB`, and marker keys shared with any built-in primitive properties are not supported. Index signatures and call or construct signatures are not supported as custom brands. All extra properties are treated as brands, including methods.
|
|
1697
|
+
|
|
1698
|
+
Nested {@link Tagged} types follow the limits described in {@link UnwrapTagged}. A single legacy {@link Opaque} layer is supported, except with a `never` token. Use {@link UnwrapTagged} to unwrap tagged objects too.
|
|
1699
|
+
|
|
1700
|
+
@see {@link UnwrapTagged}
|
|
1701
|
+
@see {@link LiteralToPrimitive}
|
|
1702
|
+
|
|
1703
|
+
@category Type
|
|
1704
|
+
*/
|
|
1705
|
+
type UnwrapBrandedPrimitive<Value> = IfNotAnyOrNever<Value, {ifNot: UnwrapBrandedPrimitiveImplementation<Value, Primitive>}>;
|
|
1706
|
+
|
|
1707
|
+
type UnwrapBrandedPrimitiveImplementation<Value, Base> = Value extends Primitive
|
|
1708
|
+
// Separate tag layers do not match a single object containing all brand properties.
|
|
1709
|
+
// `CollapseLiterals` removes `& {}` first, because TypeScript defers `keyof` on types like `` `on${string}` & {} ``.
|
|
1710
|
+
? UnwrapPrimitiveProperties<CollapseLiterals<Value extends TagContainer<unknown> ? UnwrapTagged<Value> : Value>, Base>
|
|
1711
|
+
: Value;
|
|
1712
|
+
|
|
1713
|
+
type UnwrapPrimitiveProperties<Value, Base> = Value extends infer Unbranded & Pick<Value, Exclude<keyof Value, KeysOfUnion<Base>>>
|
|
1714
|
+
? Unbranded
|
|
1715
|
+
: Value;
|
|
1716
|
+
|
|
1717
|
+
/**
|
|
1718
|
+
Returns a boolean for whether the given type is a `number` or `bigint` [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types).
|
|
1719
|
+
|
|
1720
|
+
Returns `false` for `any`, `never`, and `unknown`. Unions are normalized before classification; mixed results return `boolean`.
|
|
1721
|
+
|
|
1722
|
+
@example
|
|
1723
|
+
```
|
|
1724
|
+
import type {IsNumericLiteral} from 'type-fest';
|
|
1725
|
+
|
|
1726
|
+
type A = IsNumericLiteral<0>;
|
|
1727
|
+
//=> true
|
|
1728
|
+
|
|
1729
|
+
type B = IsNumericLiteral<number>;
|
|
1730
|
+
//=> false
|
|
1731
|
+
|
|
1732
|
+
type C = IsNumericLiteral<100n>;
|
|
1733
|
+
//=> true
|
|
824
1734
|
|
|
825
|
-
type
|
|
826
|
-
//=>
|
|
1735
|
+
type D = IsNumericLiteral<bigint>;
|
|
1736
|
+
//=> false
|
|
1737
|
+
|
|
1738
|
+
type E = IsNumericLiteral<1 | 2 | 10n | 20n>;
|
|
1739
|
+
//=> true
|
|
1740
|
+
|
|
1741
|
+
type F = IsNumericLiteral<number | bigint>;
|
|
1742
|
+
//=> false
|
|
1743
|
+
|
|
1744
|
+
type G = IsNumericLiteral<1 | bigint>;
|
|
1745
|
+
//=> boolean
|
|
827
1746
|
```
|
|
828
1747
|
|
|
829
|
-
@
|
|
830
|
-
@category
|
|
1748
|
+
@category Type Guard
|
|
1749
|
+
@category Utilities
|
|
831
1750
|
*/
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
1751
|
+
// The normalized predicate rejects `any`; only `never` needs a separate guard.
|
|
1752
|
+
// `any` is checked before `never`, so generic code that wraps the result and infers from it still sees both outcomes.
|
|
1753
|
+
// Plain primitives need no brand normalization.
|
|
1754
|
+
type IsNumericLiteral<T> = IsAny<T> extends true ? false : IsNever<T> extends true ? false : _IsNumericLiteral<CollapseLiterals<T extends object ? UnwrapBrandedPrimitive<T> : T>>;
|
|
1755
|
+
|
|
1756
|
+
// Numeric enum members accept `number`, but only constant members have known values. Comparing printed types also rejects computed members, whose numeric value is unknown.
|
|
1757
|
+
type _IsNumericLiteral<T> = T extends number | bigint
|
|
1758
|
+
? `${number}` extends `${T}`
|
|
1759
|
+
? false
|
|
1760
|
+
: `${bigint}` extends `${T}`
|
|
1761
|
+
? false
|
|
1762
|
+
: true
|
|
1763
|
+
: false;
|
|
837
1764
|
|
|
838
1765
|
/**
|
|
839
|
-
|
|
1766
|
+
Collapse literal union members into broader types already present in the union.
|
|
840
1767
|
|
|
841
|
-
|
|
1768
|
+
Use-case: Normalize a {@link LiteralUnion} for type comparisons or conditional types while preserving unrelated union members. Complements {@link ExtractLiterals}, which keeps only the literals.
|
|
1769
|
+
|
|
1770
|
+
Unlike {@link LiteralToPrimitive}, this does not widen every literal: a literal changes only when a broader member of the union already covers it. Members that are not primitives are returned unchanged. It only removes the intersection with the empty object type (`& {}`) from primitive members, which lets TypeScript merge the union. This includes the `& Record<never, never>` of {@link LiteralUnion}, because `Record<never, never>` is `{}`. This is not recursive, and it does not merge the members of a branded or tagged type, because each member keeps its own brand or tag.
|
|
842
1771
|
|
|
843
1772
|
@example
|
|
844
1773
|
```
|
|
845
|
-
import type {
|
|
1774
|
+
import type {CollapseLiterals, LiteralUnion} from 'type-fest';
|
|
846
1775
|
|
|
847
|
-
|
|
1776
|
+
type Theme = LiteralUnion<'auto' | 'dark', string>;
|
|
848
1777
|
|
|
849
|
-
type
|
|
850
|
-
|
|
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;
|
|
1778
|
+
type ThemeValue = CollapseLiterals<Theme>;
|
|
1779
|
+
//=> string
|
|
859
1780
|
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
[symbolKey]: string;
|
|
863
|
-
foo: 'bar';
|
|
864
|
-
qux?: 'baz';
|
|
865
|
-
};
|
|
1781
|
+
type OptionalTheme = CollapseLiterals<Theme | null | undefined>;
|
|
1782
|
+
//=> string | null | undefined
|
|
866
1783
|
|
|
867
|
-
type
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
// [x: `${bigint}`]: string;
|
|
876
|
-
// [x: `embedded-${number}`]: string;
|
|
877
|
-
// }
|
|
1784
|
+
type EventName = CollapseLiterals<LiteralUnion<'click' | 'onChange', `on${string}`>>;
|
|
1785
|
+
//=> 'click' | `on${string}`
|
|
1786
|
+
|
|
1787
|
+
type Size = CollapseLiterals<LiteralUnion<1 | 2 | 3, number>>;
|
|
1788
|
+
//=> number
|
|
1789
|
+
|
|
1790
|
+
type KnownTheme = CollapseLiterals<'auto' | 'dark'>;
|
|
1791
|
+
//=> 'auto' | 'dark'
|
|
878
1792
|
```
|
|
879
1793
|
|
|
880
|
-
@see {@link
|
|
881
|
-
@
|
|
1794
|
+
@see {@link LiteralUnion}
|
|
1795
|
+
@see {@link ExtractLiterals}
|
|
1796
|
+
@see {@link LiteralToPrimitive}
|
|
1797
|
+
@category Type
|
|
882
1798
|
*/
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1799
|
+
// Distribute first, so an object member in the union cannot stop the other members from collapsing.
|
|
1800
|
+
// The primitive check also keeps `{}`-like inputs away from the `infer`, which turns them into `unknown`.
|
|
1801
|
+
type CollapseLiterals<Union> = Union extends Primitive
|
|
1802
|
+
? Union extends infer Collapsed & {}
|
|
1803
|
+
? Collapsed
|
|
1804
|
+
: Union
|
|
1805
|
+
: Union;
|
|
888
1806
|
|
|
889
|
-
//
|
|
890
|
-
type SimpleMerge<Destination, Source> = Simplify<{
|
|
891
|
-
[Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
|
|
892
|
-
} & Source>;
|
|
1807
|
+
// For `@link`
|
|
893
1808
|
|
|
894
1809
|
/**
|
|
895
|
-
|
|
1810
|
+
Returns a boolean for whether the given type is a `string` [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types).
|
|
896
1811
|
|
|
897
|
-
|
|
1812
|
+
Returns `false` for `any`, `never`, and `unknown`. Unions are normalized before classification; mixed results return `boolean`. Use {@link IsTemplateLiteral} to classify the open-ended string patterns, like `` `on${string}` ``.
|
|
1813
|
+
|
|
1814
|
+
The implementation of this type is inspired by the trick mentioned in this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
898
1815
|
|
|
899
1816
|
@example
|
|
900
1817
|
```
|
|
901
|
-
import type {
|
|
1818
|
+
import type {IsStringLiteral} from 'type-fest';
|
|
902
1819
|
|
|
903
|
-
type
|
|
904
|
-
|
|
905
|
-
b: number;
|
|
906
|
-
};
|
|
1820
|
+
type A = IsStringLiteral<'foo'>;
|
|
1821
|
+
//=> true
|
|
907
1822
|
|
|
908
|
-
type
|
|
909
|
-
|
|
910
|
-
c: boolean;
|
|
911
|
-
};
|
|
1823
|
+
type B = IsStringLiteral<string>;
|
|
1824
|
+
//=> false
|
|
912
1825
|
|
|
913
|
-
//
|
|
914
|
-
type
|
|
915
|
-
//=>
|
|
1826
|
+
// String types with infinite set of possible values return `false`
|
|
1827
|
+
type C = IsStringLiteral<`on${string}`>;
|
|
1828
|
+
//=> false
|
|
916
1829
|
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1830
|
+
type D = IsStringLiteral<Uppercase<string>>;
|
|
1831
|
+
//=> false
|
|
1832
|
+
|
|
1833
|
+
type E = IsStringLiteral<'foo' | 'bar' | 'baz'>;
|
|
1834
|
+
//=> true
|
|
1835
|
+
|
|
1836
|
+
type F = IsStringLiteral<'sm' | 'md' | 'lg' | `${number}px`>;
|
|
1837
|
+
//=> boolean
|
|
920
1838
|
```
|
|
921
1839
|
|
|
922
1840
|
@example
|
|
923
1841
|
```
|
|
924
|
-
import type {
|
|
1842
|
+
import type {IsStringLiteral} from 'type-fest';
|
|
925
1843
|
|
|
926
|
-
type
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1844
|
+
type StringLength<S extends string, Counter extends never[] = []> =
|
|
1845
|
+
IsStringLiteral<S> extends true
|
|
1846
|
+
? S extends `${string}${infer Tail}`
|
|
1847
|
+
? StringLength<Tail, [...Counter, never]>
|
|
1848
|
+
: Counter['length']
|
|
1849
|
+
: number; // return `number` for non-literal string types
|
|
932
1850
|
|
|
933
|
-
type
|
|
934
|
-
|
|
935
|
-
[x: symbol]: unknown;
|
|
936
|
-
bar: Date;
|
|
937
|
-
baz: boolean;
|
|
938
|
-
};
|
|
1851
|
+
type L1 = StringLength<'foobar'>;
|
|
1852
|
+
//=> 6
|
|
939
1853
|
|
|
940
|
-
|
|
941
|
-
//=>
|
|
942
|
-
// [x: string]: unknown;
|
|
943
|
-
// [x: number]: number;
|
|
944
|
-
// [x: symbol]: unknown;
|
|
945
|
-
// foo: string;
|
|
946
|
-
// bar: Date;
|
|
947
|
-
// baz: boolean;
|
|
948
|
-
// }
|
|
949
|
-
```
|
|
1854
|
+
type L2 = StringLength<Lowercase<string>>;
|
|
1855
|
+
//=> number
|
|
950
1856
|
|
|
951
|
-
|
|
1857
|
+
type L3 = StringLength<`${number}`>;
|
|
1858
|
+
//=> number
|
|
1859
|
+
```
|
|
952
1860
|
|
|
953
|
-
@
|
|
954
|
-
@category
|
|
1861
|
+
@category Type Guard
|
|
1862
|
+
@category Utilities
|
|
955
1863
|
*/
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1864
|
+
// The normalized predicate rejects `any`; only `never` needs a separate guard.
|
|
1865
|
+
// `any` is checked before `never`, so generic code that wraps the result and infers from it still sees both outcomes.
|
|
1866
|
+
// Plain primitives need no brand normalization.
|
|
1867
|
+
type IsStringLiteral<S> = IsAny<S> extends true ? false : IsNever<S> extends true ? false : _IsStringLiteral<CollapseLiterals<S extends object ? UnwrapBrandedPrimitive<S> : S>>;
|
|
1868
|
+
|
|
1869
|
+
type _IsStringLiteral<S> =
|
|
1870
|
+
// If `S` is an infinite string type (e.g., `on${string}`), `Record<S, never>` produces an index signature,
|
|
1871
|
+
// and since `{}` extends index signatures, the result becomes `false`.
|
|
1872
|
+
S extends string
|
|
1873
|
+
? {} extends Record<S, never>
|
|
1874
|
+
? false
|
|
1875
|
+
: true
|
|
1876
|
+
: false;
|
|
968
1877
|
|
|
969
1878
|
/**
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
1879
|
+
Matches a single ASCII punctuation character.
|
|
1880
|
+
|
|
1881
|
+
Includes the 32 printable ASCII characters other than letters, digits, and space, including symbols such as `$`, `+`, and `~`, as in [Python's `string.punctuation`](https://docs.python.org/3/library/string.html#string.punctuation). Excludes whitespace and non-ASCII punctuation.
|
|
1882
|
+
|
|
1883
|
+
Useful for type-level string parsing and delimiter validation.
|
|
975
1884
|
|
|
976
1885
|
@example
|
|
977
1886
|
```
|
|
978
|
-
type
|
|
979
|
-
url: string;
|
|
980
|
-
size: number;
|
|
981
|
-
thumbnailUrl: string;
|
|
982
|
-
};
|
|
1887
|
+
import type {AsciiPunctuationCharacter} from 'type-fest';
|
|
983
1888
|
|
|
984
|
-
type
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
1889
|
+
type Separator = Extract<',' | ';' | ' ' | 'a', AsciiPunctuationCharacter>;
|
|
1890
|
+
//=> ',' | ';'
|
|
1891
|
+
|
|
1892
|
+
const delimiter: AsciiPunctuationCharacter = ':';
|
|
1893
|
+
// @ts-expect-error
|
|
1894
|
+
const invalidDelimiter: AsciiPunctuationCharacter = '::';
|
|
1895
|
+
```
|
|
989
1896
|
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1897
|
+
@category String
|
|
1898
|
+
@category Template literal
|
|
1899
|
+
*/
|
|
1900
|
+
type AsciiPunctuationCharacter =
|
|
1901
|
+
| '!'
|
|
1902
|
+
| '"'
|
|
1903
|
+
| '#'
|
|
1904
|
+
| '$'
|
|
1905
|
+
| '%'
|
|
1906
|
+
| '&'
|
|
1907
|
+
| '\''
|
|
1908
|
+
| '('
|
|
1909
|
+
| ')'
|
|
1910
|
+
| '*'
|
|
1911
|
+
| '+'
|
|
1912
|
+
| ','
|
|
1913
|
+
| '-'
|
|
1914
|
+
| '.'
|
|
1915
|
+
| '/'
|
|
1916
|
+
| ':'
|
|
1917
|
+
| ';'
|
|
1918
|
+
| '<'
|
|
1919
|
+
| '='
|
|
1920
|
+
| '>'
|
|
1921
|
+
| '?'
|
|
1922
|
+
| '@'
|
|
1923
|
+
| '['
|
|
1924
|
+
| '\\'
|
|
1925
|
+
| ']'
|
|
1926
|
+
| '^'
|
|
1927
|
+
| '_'
|
|
1928
|
+
| '`'
|
|
1929
|
+
| '{'
|
|
1930
|
+
| '|'
|
|
1931
|
+
| '}'
|
|
1932
|
+
| '~';
|
|
993
1933
|
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
//=> string | number
|
|
1934
|
+
/**
|
|
1935
|
+
Convert a string or number key to its template literal representation.
|
|
997
1936
|
|
|
998
|
-
|
|
999
|
-
type Any = HomomorphicPick<{a: 1; b: 2} | {c: 3}, any>;
|
|
1000
|
-
//=> {a: 1; b: 2} | {c: 3}
|
|
1937
|
+
Note: This type is not the return type of the `.toString()` function.
|
|
1001
1938
|
|
|
1002
|
-
|
|
1003
|
-
type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>;
|
|
1004
|
-
//=> {}
|
|
1939
|
+
Keep this separate from the public `ToString`: internal key and path matching relies on preserving branded template literal patterns and `${any}`.
|
|
1005
1940
|
*/
|
|
1006
|
-
type
|
|
1007
|
-
[P in keyof T as Extract<P, Keys>]: T[P]
|
|
1008
|
-
};
|
|
1941
|
+
type KeyToString<Key> = Key extends string | number ? `${Key}` : never;
|
|
1009
1942
|
|
|
1010
1943
|
/**
|
|
1011
|
-
|
|
1944
|
+
Remove brands from property paths while preserving empty intersections used by `LiteralUnion`.
|
|
1945
|
+
|
|
1946
|
+
Distribute before normalization so a wide path cannot erase another member's known segments.
|
|
1012
1947
|
|
|
1013
1948
|
@example
|
|
1014
1949
|
```
|
|
1015
|
-
type
|
|
1016
|
-
//=>
|
|
1950
|
+
type Path = UnwrapPathBrand<'users.name' & {readonly brand: unique symbol}>;
|
|
1951
|
+
//=> 'users.name'
|
|
1017
1952
|
```
|
|
1018
1953
|
*/
|
|
1019
|
-
type
|
|
1020
|
-
|
|
1954
|
+
type UnwrapPathBrand<Path> = Path extends unknown
|
|
1955
|
+
? Exclude<keyof CollapseLiterals<Path>, keyof string | keyof number> extends never ? Path : UnwrapBrandedPrimitive<Path>
|
|
1956
|
+
: never;
|
|
1021
1957
|
|
|
1022
1958
|
/**
|
|
1023
|
-
|
|
1959
|
+
Matches the hidden `Infinity` type.
|
|
1024
1960
|
|
|
1025
|
-
|
|
1026
|
-
```
|
|
1027
|
-
type User = {
|
|
1028
|
-
readonly id: string;
|
|
1029
|
-
name: string;
|
|
1030
|
-
};
|
|
1961
|
+
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
|
|
1031
1962
|
|
|
1032
|
-
|
|
1033
|
-
readonly id: string;
|
|
1034
|
-
readonly author: string;
|
|
1035
|
-
body: string;
|
|
1036
|
-
};
|
|
1963
|
+
@see {@link NegativeInfinity}
|
|
1037
1964
|
|
|
1038
|
-
|
|
1039
|
-
//=> "id" | "author"
|
|
1040
|
-
```
|
|
1965
|
+
@category Numeric
|
|
1041
1966
|
*/
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1967
|
+
// See https://github.com/microsoft/TypeScript/issues/31752
|
|
1968
|
+
// eslint-disable-next-line no-loss-of-precision
|
|
1969
|
+
type PositiveInfinity = 1e999;
|
|
1045
1970
|
|
|
1046
1971
|
/**
|
|
1047
|
-
|
|
1972
|
+
Matches the hidden `-Infinity` type.
|
|
1048
1973
|
|
|
1049
|
-
|
|
1050
|
-
```
|
|
1051
|
-
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
1052
|
-
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
1053
|
-
type SpecifiedOptions = {leavesOnly: true};
|
|
1974
|
+
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/32277) if you want to have this type as a built-in in TypeScript.
|
|
1054
1975
|
|
|
1055
|
-
|
|
1056
|
-
//=> {maxRecursionDepth: 10; leavesOnly: true}
|
|
1057
|
-
```
|
|
1976
|
+
@see {@link PositiveInfinity}
|
|
1058
1977
|
|
|
1059
|
-
@
|
|
1060
|
-
|
|
1061
|
-
//
|
|
1978
|
+
@category Numeric
|
|
1979
|
+
*/
|
|
1980
|
+
// See https://github.com/microsoft/TypeScript/issues/31752
|
|
1981
|
+
// eslint-disable-next-line no-loss-of-precision
|
|
1982
|
+
type NegativeInfinity = -1e999;
|
|
1062
1983
|
|
|
1063
|
-
|
|
1064
|
-
type DefaultPathsOptions = {maxRecursionDepth: 10};
|
|
1065
|
-
type SpecifiedOptions = {};
|
|
1984
|
+
// For `@link`
|
|
1066
1985
|
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
// Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
|
|
1070
|
-
```
|
|
1986
|
+
/**
|
|
1987
|
+
Converts a numeric string to a number.
|
|
1071
1988
|
|
|
1072
1989
|
@example
|
|
1073
1990
|
```
|
|
1074
|
-
|
|
1991
|
+
import type {StringToNumber} from 'type-fest';
|
|
1992
|
+
|
|
1993
|
+
type PositiveInteger = StringToNumber<'1234'>;
|
|
1994
|
+
//=> 1234
|
|
1075
1995
|
|
|
1076
|
-
type
|
|
1077
|
-
|
|
1078
|
-
type SpecifiedOptions = {};
|
|
1996
|
+
type NegativeInteger = StringToNumber<'-1234'>;
|
|
1997
|
+
//=> -1234
|
|
1079
1998
|
|
|
1080
|
-
type
|
|
1081
|
-
|
|
1082
|
-
|
|
1999
|
+
type PositiveFloat = StringToNumber<'1234.56'>;
|
|
2000
|
+
//=> 1234.56
|
|
2001
|
+
|
|
2002
|
+
type NegativeFloat = StringToNumber<'-1234.56'>;
|
|
2003
|
+
//=> -1234.56
|
|
2004
|
+
|
|
2005
|
+
type PositiveInfinity = StringToNumber<'Infinity'>;
|
|
2006
|
+
//=> Infinity
|
|
2007
|
+
|
|
2008
|
+
type NegativeInfinity = StringToNumber<'-Infinity'>;
|
|
2009
|
+
//=> -Infinity
|
|
1083
2010
|
```
|
|
1084
2011
|
|
|
2012
|
+
Note: Some strings, such as `'1.50'`, `'0b10'`, `'12_345'`, or an integer too large to be represented exactly like `'9007199254740993'`, may look like they can be converted to numbers, but they don't actually have corresponding numeric literals. So, in such cases, this type produces `never`. See [type-fest#1446](https://github.com/sindresorhus/type-fest/pull/1446) for more details.
|
|
2013
|
+
|
|
1085
2014
|
@example
|
|
1086
2015
|
```
|
|
1087
|
-
|
|
2016
|
+
import type {StringToNumber} from 'type-fest';
|
|
2017
|
+
|
|
2018
|
+
type FractionalsEndingInZero = StringToNumber<'1.50'>;
|
|
2019
|
+
//=> never
|
|
2020
|
+
|
|
2021
|
+
type NonDecimalBases = StringToNumber<'0b10' | '0o10' | '0x10'>;
|
|
2022
|
+
//=> never
|
|
1088
2023
|
|
|
1089
|
-
type
|
|
1090
|
-
|
|
1091
|
-
type SpecifiedOptions = {leavesOnly: 'yes'};
|
|
2024
|
+
type NumericSeparators = StringToNumber<'12_345'>;
|
|
2025
|
+
//=> never
|
|
1092
2026
|
|
|
1093
|
-
type
|
|
1094
|
-
|
|
1095
|
-
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
2027
|
+
type TooLarge = StringToNumber<'9007199254740993'>;
|
|
2028
|
+
//=> never
|
|
1096
2029
|
```
|
|
2030
|
+
|
|
2031
|
+
@see {@link StringToBoolean} - For parsing a boolean string.
|
|
2032
|
+
|
|
2033
|
+
@category String
|
|
2034
|
+
@category Numeric
|
|
2035
|
+
@category Template literal
|
|
1097
2036
|
*/
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
2037
|
+
// The parser already returns `number` for `any` and distributes `never` to `never`.
|
|
2038
|
+
type StringToNumber<S extends string> = _StringToNumber<S extends object ? UnwrapBrandedPrimitive<S> : S>;
|
|
2039
|
+
|
|
2040
|
+
type _StringToNumber<S extends string> =
|
|
2041
|
+
S extends `${infer N extends number}`
|
|
2042
|
+
? number extends N
|
|
2043
|
+
? `${number}` extends S
|
|
2044
|
+
? N
|
|
2045
|
+
: never
|
|
2046
|
+
: N
|
|
2047
|
+
: string extends S
|
|
2048
|
+
? number
|
|
2049
|
+
: S extends 'Infinity'
|
|
2050
|
+
? PositiveInfinity
|
|
2051
|
+
: S extends '-Infinity'
|
|
2052
|
+
? NegativeInfinity
|
|
2053
|
+
: never;
|
|
2054
|
+
|
|
2055
|
+
// For `@link`
|
|
1110
2056
|
|
|
1111
2057
|
/**
|
|
1112
|
-
|
|
1113
|
-
*/
|
|
1114
|
-
type SomeExtendOptions = {
|
|
1115
|
-
/**
|
|
1116
|
-
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
2058
|
+
Resolve a property key to the matching key type in an object, converting between numeric and string forms when needed.
|
|
1117
2059
|
|
|
1118
|
-
|
|
1119
|
-
- When set to `false`, `never` is treated as a bottom type, and behaves as it normally would.
|
|
2060
|
+
Useful when composing generic property access utilities that accept either `0` or `'0'` for the same property. Returns `never` if no key matches.
|
|
1120
2061
|
|
|
1121
|
-
|
|
2062
|
+
Keys assignable to `keyof ObjectType` are returned unchanged, including keys covered by index signatures. Otherwise, numeric keys are tried as strings, and numeric strings as numbers only if converting back preserves their spelling. For example, `'01'` does not match `1`.
|
|
1122
2063
|
|
|
1123
|
-
|
|
1124
|
-
```
|
|
1125
|
-
import type {SomeExtend} from 'type-fest';
|
|
2064
|
+
Distributes over a union of keys. For a union of objects, only keys in `keyof ObjectType` are considered, so a key must be common to all members. Plain strings do not select string enum keys. Array and tuple indices are not bounds-checked.
|
|
1126
2065
|
|
|
1127
|
-
|
|
1128
|
-
|
|
2066
|
+
@example
|
|
2067
|
+
```
|
|
2068
|
+
import type {MatchingKey} from 'type-fest';
|
|
1129
2069
|
|
|
1130
|
-
|
|
1131
|
-
|
|
2070
|
+
type StatusMessages = {
|
|
2071
|
+
200: 'OK';
|
|
2072
|
+
'404': 'Not found';
|
|
2073
|
+
};
|
|
1132
2074
|
|
|
1133
|
-
|
|
1134
|
-
|
|
2075
|
+
type SuccessKey = MatchingKey<StatusMessages, '200'>;
|
|
2076
|
+
//=> 200
|
|
1135
2077
|
|
|
1136
|
-
|
|
1137
|
-
|
|
2078
|
+
type NotFoundKey = MatchingKey<StatusMessages, 404>;
|
|
2079
|
+
//=> '404'
|
|
1138
2080
|
|
|
1139
|
-
|
|
1140
|
-
//=> true
|
|
2081
|
+
type PickByKey<ObjectType extends object, Key extends PropertyKey> = Pick<ObjectType, MatchingKey<ObjectType, Key>>;
|
|
1141
2082
|
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
*/
|
|
1146
|
-
strictNever?: boolean;
|
|
1147
|
-
};
|
|
2083
|
+
type Success = PickByKey<StatusMessages, '200'>;
|
|
2084
|
+
//=> {200: 'OK'}
|
|
2085
|
+
```
|
|
1148
2086
|
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
2087
|
+
@see {@link PropertyValue} to get the value of the matching property.
|
|
2088
|
+
|
|
2089
|
+
@category Object
|
|
2090
|
+
*/
|
|
2091
|
+
type MatchingKey<ObjectType extends object, Key extends PropertyKey> =
|
|
2092
|
+
Key extends keyof ObjectType
|
|
2093
|
+
? Key
|
|
2094
|
+
: KeyToString<Key> extends keyof ObjectType
|
|
2095
|
+
? KeyToString<Key>
|
|
2096
|
+
: Key extends `${infer NumberKey extends number}`
|
|
2097
|
+
// A numeric-looking string names a number key only when its spelling survives the conversion.
|
|
2098
|
+
? `${NumberKey}` extends Key
|
|
2099
|
+
? NumberKey extends keyof ObjectType
|
|
2100
|
+
? NumberKey
|
|
2101
|
+
: never
|
|
2102
|
+
: never
|
|
2103
|
+
: never;
|
|
1152
2104
|
|
|
1153
2105
|
/**
|
|
1154
|
-
|
|
2106
|
+
Flatten an object type. This is the plain definition `Simplify` had before it started returning a function, a class constructor, or a branded primitive as is.
|
|
2107
|
+
|
|
2108
|
+
Internal types use this instead of `Simplify`, because they only flatten object types they built themselves, where any call signature is already dropped or handled separately and no branded primitive can appear, so they do not need that check. Use `Simplify` if the input can be a function, a class constructor, or a branded primitive. Keeping the check out of them avoids its cost in every type that flattens its result, and avoids the risk of "excessively deep" errors in user code, which a conditional in `Simplify` once caused for types like `SetRequired`. See https://github.com/sindresorhus/type-fest/issues/436.
|
|
2109
|
+
*/
|
|
2110
|
+
type SimplifyObject<Type> = {[KeyType in keyof Type]: Type[KeyType]} & {};
|
|
2111
|
+
|
|
2112
|
+
/**
|
|
2113
|
+
Returns whether the given key of `ObjectType` has the `readonly` modifier.
|
|
2114
|
+
|
|
2115
|
+
The key belongs to the object, so no distribution or `any` handling is needed.
|
|
2116
|
+
*/
|
|
2117
|
+
type IsReadonlyProperty<ObjectType, Key extends keyof ObjectType> =
|
|
2118
|
+
(
|
|
2119
|
+
// An index signature does not satisfy a required property, so this only matches a declared key. `Required` keeps optional declared keys, and `Record` treats `0` and `'0'` as the same property.
|
|
2120
|
+
Required<ObjectType> extends Record<Key, unknown>
|
|
2121
|
+
? Key
|
|
2122
|
+
// A mapped type over a literal key copies only the modifier of a declared property, so map over the index signatures that cover the key instead. Like in TypeScript, a `number` index signature also covers numeric string keys, and a `string` index signature applies only when no other index signature covers the key. The mapped type visits each index signature on its own, while `keyof` would merge a template literal signature into `string`.
|
|
2123
|
+
: keyof {[Property in keyof ObjectType as Key extends Property | (number extends Property ? `${number}` : never) ? (string extends Property ? never : Property) : never]: never} extends infer SpecificKey
|
|
2124
|
+
? [SpecificKey] extends [never] ? string : SpecificKey
|
|
2125
|
+
: never
|
|
2126
|
+
) extends infer MappedKey extends keyof ObjectType
|
|
2127
|
+
? IsEqual<
|
|
2128
|
+
{[Property in MappedKey]: ObjectType[Property]},
|
|
2129
|
+
{readonly [Property in MappedKey]: ObjectType[Property]}
|
|
2130
|
+
>
|
|
2131
|
+
: never;
|
|
2132
|
+
|
|
2133
|
+
/**
|
|
2134
|
+
Normalize keys by including string and number representations wherever applicable.
|
|
1155
2135
|
|
|
1156
2136
|
@example
|
|
1157
|
-
```
|
|
1158
|
-
|
|
2137
|
+
```ts
|
|
2138
|
+
type A = NormalizedKeys<0 | '1'>;
|
|
2139
|
+
//=> 0 | '0' | 1 | '1'
|
|
1159
2140
|
|
|
1160
|
-
type
|
|
1161
|
-
//=>
|
|
2141
|
+
type B = NormalizedKeys<string>;
|
|
2142
|
+
//=> string | number
|
|
1162
2143
|
|
|
1163
|
-
type
|
|
1164
|
-
//=>
|
|
2144
|
+
type C = NormalizedKeys<number>;
|
|
2145
|
+
//=> number | `${number}`
|
|
1165
2146
|
|
|
1166
|
-
type
|
|
1167
|
-
//=>
|
|
2147
|
+
type D = NormalizedKeys<symbol | 'foo'>;
|
|
2148
|
+
//=> symbol | 'foo'
|
|
2149
|
+
```
|
|
2150
|
+
*/
|
|
2151
|
+
type NormalizedKeys<Keys extends PropertyKey> =
|
|
2152
|
+
| Keys
|
|
2153
|
+
| (string extends Keys ? number : never)
|
|
2154
|
+
| StringToNumber<Keys & string>
|
|
2155
|
+
| KeyToString<Keys & number>;
|
|
1168
2156
|
|
|
1169
|
-
|
|
1170
|
-
|
|
2157
|
+
/**
|
|
2158
|
+
Get the given keys with their numeric and string aliases, including the runtime string spelling of enum keys.
|
|
2159
|
+
|
|
2160
|
+
@example
|
|
2161
|
+
```ts
|
|
2162
|
+
enum Color {
|
|
2163
|
+
Red = 'red',
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
type A = KeyAliases<0 | Color.Red>;
|
|
2167
|
+
//=> 0 | '0' | Color.Red | 'red'
|
|
1171
2168
|
```
|
|
2169
|
+
*/
|
|
2170
|
+
type KeyAliases<Keys extends PropertyKey> = NormalizedKeys<Keys | KeyToString<Keys>>;
|
|
1172
2171
|
|
|
1173
|
-
|
|
2172
|
+
/**
|
|
2173
|
+
Extract all required keys from the given type.
|
|
1174
2174
|
|
|
1175
|
-
|
|
1176
|
-
// @exactOptionalPropertyTypes: true
|
|
1177
|
-
import type {SomeExtend} from 'type-fest';
|
|
2175
|
+
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...
|
|
1178
2176
|
|
|
1179
|
-
|
|
1180
|
-
//=> true
|
|
2177
|
+
@example
|
|
1181
2178
|
```
|
|
2179
|
+
import type {RequiredKeysOf} from 'type-fest';
|
|
1182
2180
|
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
2181
|
+
declare function createValidation<
|
|
2182
|
+
Entity extends object,
|
|
2183
|
+
Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>,
|
|
2184
|
+
>(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean;
|
|
1186
2185
|
|
|
1187
|
-
type
|
|
1188
|
-
|
|
2186
|
+
type User = {
|
|
2187
|
+
name: string;
|
|
2188
|
+
surname: string;
|
|
2189
|
+
luckyNumber?: number;
|
|
2190
|
+
};
|
|
1189
2191
|
|
|
1190
|
-
|
|
1191
|
-
|
|
2192
|
+
const validator1 = createValidation<User>('name', value => value.length < 25);
|
|
2193
|
+
const validator2 = createValidation<User>('surname', value => value.length < 25);
|
|
2194
|
+
|
|
2195
|
+
// @ts-expect-error
|
|
2196
|
+
const validator3 = createValidation<User>('luckyNumber', value => value > 0);
|
|
2197
|
+
// Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'.
|
|
1192
2198
|
```
|
|
1193
2199
|
|
|
1194
|
-
|
|
2200
|
+
Known limitations:
|
|
2201
|
+
- An index signature is reported as a required key, so `RequiredKeysOf<Record<string, unknown>>` is `string` rather than `never`. The signature satisfies the required-property check against `Record<Key, Type[Key]>`, even though no particular property has to be present.
|
|
2202
|
+
- A union reports the keys of each of its members, so the result can name a key that is not a key of the union itself. `keyof` of a union is the intersection of its members' keys, so `RequiredKeysOf<{a: string} | {b: number}>` is `'a' | 'b'` while `keyof` of the same union is `never`. Read one member at a time if you need a key that is valid for the whole union.
|
|
1195
2203
|
|
|
1196
2204
|
@category Utilities
|
|
1197
|
-
@category Array
|
|
1198
2205
|
*/
|
|
1199
|
-
type
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
? IsNever<First> extends true
|
|
1205
|
-
? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true
|
|
1206
|
-
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, return `true`.
|
|
1207
|
-
? true
|
|
1208
|
-
: _SomeExtend<Rest, Type, Options>
|
|
1209
|
-
: First extends Type
|
|
1210
|
-
? true
|
|
1211
|
-
: _SomeExtend<Rest, Type, Options>
|
|
1212
|
-
: false,
|
|
1213
|
-
false, false>;
|
|
2206
|
+
type RequiredKeysOf<Type extends object> =
|
|
2207
|
+
IsAny<Type> extends true ? keyof Type
|
|
2208
|
+
: Type extends unknown // For distributing `Type`
|
|
2209
|
+
? (keyof {[Key in keyof Type as Type extends Record<Key, Type[Key]> ? Key : never]: never}) & keyof Type
|
|
2210
|
+
: never; // Should never happen
|
|
1214
2211
|
|
|
1215
|
-
|
|
1216
|
-
Returns a boolean for whether any of the given elements is `true`.
|
|
2212
|
+
// For `@link`
|
|
1217
2213
|
|
|
1218
|
-
|
|
1219
|
-
|
|
2214
|
+
/**
|
|
2215
|
+
Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aid with assignability.
|
|
1220
2216
|
|
|
1221
2217
|
@example
|
|
1222
2218
|
```
|
|
1223
|
-
import type {
|
|
1224
|
-
|
|
1225
|
-
type FFT = OrAll<[false, false, true]>;
|
|
1226
|
-
//=> true
|
|
2219
|
+
import type {Simplify} from 'type-fest';
|
|
1227
2220
|
|
|
1228
|
-
type
|
|
1229
|
-
|
|
1230
|
-
|
|
2221
|
+
type PositionProps = {
|
|
2222
|
+
top: number;
|
|
2223
|
+
left: number;
|
|
2224
|
+
};
|
|
1231
2225
|
|
|
1232
|
-
|
|
1233
|
-
|
|
2226
|
+
type SizeProps = {
|
|
2227
|
+
width: number;
|
|
2228
|
+
height: number;
|
|
2229
|
+
};
|
|
1234
2230
|
|
|
1235
|
-
|
|
2231
|
+
// In your editor, hovering over `Props` will show a flattened object with all the properties.
|
|
2232
|
+
type Props = Simplify<PositionProps & SizeProps>;
|
|
1236
2233
|
```
|
|
1237
|
-
import type {OrAll} from 'type-fest';
|
|
1238
|
-
|
|
1239
|
-
type A = OrAll<[false, boolean]>;
|
|
1240
|
-
//=> boolean
|
|
1241
2234
|
|
|
1242
|
-
type
|
|
1243
|
-
//=> true
|
|
1244
|
-
```
|
|
2235
|
+
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.
|
|
1245
2236
|
|
|
1246
|
-
|
|
2237
|
+
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`.
|
|
1247
2238
|
|
|
1248
2239
|
@example
|
|
1249
2240
|
```
|
|
1250
|
-
import type {
|
|
2241
|
+
import type {Simplify} from 'type-fest';
|
|
1251
2242
|
|
|
1252
|
-
|
|
1253
|
-
|
|
2243
|
+
interface SomeInterface {
|
|
2244
|
+
foo: number;
|
|
2245
|
+
bar?: string;
|
|
2246
|
+
baz: number | undefined;
|
|
2247
|
+
}
|
|
1254
2248
|
|
|
1255
|
-
type
|
|
1256
|
-
|
|
2249
|
+
type SomeType = {
|
|
2250
|
+
foo: number;
|
|
2251
|
+
bar?: string;
|
|
2252
|
+
baz: number | undefined;
|
|
2253
|
+
};
|
|
1257
2254
|
|
|
1258
|
-
|
|
1259
|
-
|
|
2255
|
+
const literal = {foo: 123, bar: 'hello', baz: 456};
|
|
2256
|
+
const someType: SomeType = literal;
|
|
2257
|
+
const someInterface: SomeInterface = literal;
|
|
1260
2258
|
|
|
1261
|
-
|
|
1262
|
-
|
|
2259
|
+
declare function fn(object: Record<string, unknown>): void;
|
|
2260
|
+
|
|
2261
|
+
fn(literal); // Good: literal object type is sealed
|
|
2262
|
+
fn(someType); // Good: type is sealed
|
|
2263
|
+
// @ts-expect-error
|
|
2264
|
+
fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
|
|
2265
|
+
fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
|
|
1263
2266
|
```
|
|
1264
2267
|
|
|
1265
|
-
|
|
2268
|
+
Only the top level is flattened. Property values are kept as is, and so are the elements of an array or a tuple, which keeps its shape. Use {@link SimplifyDeep} to flatten them too.
|
|
1266
2269
|
|
|
1267
2270
|
@example
|
|
1268
2271
|
```
|
|
1269
|
-
import type {
|
|
2272
|
+
import type {Simplify} from 'type-fest';
|
|
1270
2273
|
|
|
1271
|
-
type
|
|
1272
|
-
//=> boolean
|
|
2274
|
+
type Point = {x: number} & {y: number};
|
|
1273
2275
|
|
|
1274
|
-
type
|
|
1275
|
-
//=>
|
|
1276
|
-
```
|
|
2276
|
+
type A = Simplify<{start: Point} & {end: Point}>;
|
|
2277
|
+
//=> {start: Point; end: Point}
|
|
1277
2278
|
|
|
1278
|
-
|
|
2279
|
+
type B = Simplify<[label: string, point?: Point]>;
|
|
2280
|
+
//=> [label: string, point?: Point]
|
|
2281
|
+
```
|
|
1279
2282
|
|
|
1280
|
-
|
|
1281
|
-
@see {@link AndAll}
|
|
1282
|
-
*/
|
|
1283
|
-
type OrAll<T extends readonly boolean[]> = SomeExtend<T, true>;
|
|
2283
|
+
A function or a class constructor is returned as is, because its call and construct signatures cannot be flattened into an object. To get only the properties of a function, use `Simplify<Omit<Type, never>>`.
|
|
1284
2284
|
|
|
1285
|
-
|
|
1286
|
-
Returns a boolean for whether either of two given types is true.
|
|
2285
|
+
A primitive is also returned as is. A branded primitive like `Tagged<string, 'UserId'>` or `string & {}` is returned as is too, because flattening it would turn it into an object and remove the primitive. A union that includes a function, a class constructor, or a branded primitive is returned as is, so its other members are not flattened. A plain primitive in a union does not stop its other members from being flattened.
|
|
1287
2286
|
|
|
1288
|
-
|
|
2287
|
+
TypeScript does not resolve a mapped type over a template literal type intersected with `{}`, so ``Simplify<`on${string}` & {}>`` stays unresolved and is not assignable to `string`. Use `Record<never, never>` instead of `{}`, like `LiteralUnion` does.
|
|
1289
2288
|
|
|
1290
2289
|
@example
|
|
1291
2290
|
```
|
|
1292
|
-
import type {
|
|
2291
|
+
import type {Simplify} from 'type-fest';
|
|
1293
2292
|
|
|
1294
|
-
type
|
|
1295
|
-
//=> true
|
|
2293
|
+
type Format = (value: string) => string;
|
|
1296
2294
|
|
|
1297
|
-
type
|
|
1298
|
-
//=>
|
|
2295
|
+
type A = Simplify<Format>;
|
|
2296
|
+
//=> (value: string) => string
|
|
1299
2297
|
|
|
1300
|
-
type
|
|
1301
|
-
//=>
|
|
2298
|
+
type B = Simplify<Format & {description: string}>;
|
|
2299
|
+
//=> Format & {description: string}
|
|
1302
2300
|
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
2301
|
+
// `Omit` drops the call signature, so this gives only the properties.
|
|
2302
|
+
type C = Simplify<Omit<Format & {description: string}, never>>;
|
|
2303
|
+
//=> {description: string}
|
|
1306
2304
|
|
|
1307
|
-
|
|
1308
|
-
For example, `Or<false, boolean>` expands to `Or<false, true> | Or<false, false>`, which simplifies to `true | false` (i.e., `boolean`).
|
|
2305
|
+
type UserId = string & {brand: 'UserId'};
|
|
1309
2306
|
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
import type {Or} from 'type-fest';
|
|
2307
|
+
type D = Simplify<UserId>;
|
|
2308
|
+
//=> string & {brand: 'UserId'}
|
|
1313
2309
|
|
|
1314
|
-
|
|
1315
|
-
|
|
2310
|
+
// A plain primitive does not stop the other members from being flattened.
|
|
2311
|
+
type E = Simplify<'auto' | ({width: number} & {height: number})>;
|
|
2312
|
+
//=> 'auto' | {width: number; height: number}
|
|
1316
2313
|
|
|
1317
|
-
|
|
1318
|
-
|
|
2314
|
+
// A branded primitive does, so the union is returned as is.
|
|
2315
|
+
type F = Simplify<UserId | ({width: number} & {height: number})>;
|
|
2316
|
+
//=> UserId | ({width: number} & {height: number})
|
|
2317
|
+
```
|
|
1319
2318
|
|
|
1320
|
-
type
|
|
1321
|
-
//=> true
|
|
2319
|
+
A built-in object like `Date`, `Map`, or `Promise`, and an array or a tuple with extra properties like `string[] & {total: number}`, is flattened into an object of all its members. The result is still assignable to and from the original type, but it makes type hints long, so do not wrap these types in `Simplify`.
|
|
1322
2320
|
|
|
1323
|
-
|
|
1324
|
-
|
|
2321
|
+
@see https://github.com/microsoft/TypeScript/issues/15300
|
|
2322
|
+
@see {@link SimplifyDeep}
|
|
2323
|
+
@category Object
|
|
2324
|
+
*/
|
|
2325
|
+
// Internal types use `SimplifyObject` instead, which leaves out the check for functions, class constructors, and branded primitives. See its comment for why.
|
|
2326
|
+
type Simplify<T> =
|
|
2327
|
+
// The check is not distributive, so that a generic `T` stays assignable to `Simplify<T>`, because it is assignable to both branches.
|
|
2328
|
+
[BrandedPrimitive<T> | Extract<T, ((...arguments_: never) => unknown) | (abstract new (...arguments_: never) => unknown)>] extends [never]
|
|
2329
|
+
? {[KeyType in keyof T]: T[KeyType]} & {}
|
|
2330
|
+
: T;
|
|
2331
|
+
|
|
2332
|
+
// The members of `Type` that are a primitive intersected with an object type, like `Tagged<string, 'UserId'>` or `string & {}`. A homomorphic mapped type, like the one in `Simplify`, returns a plain primitive as is, but turns a branded primitive into an object of all its members, which removes the primitive.
|
|
2333
|
+
type BrandedPrimitive<Type> = Type extends Primitive
|
|
2334
|
+
? {[KeyType in keyof Type]: Type[KeyType]} extends Primitive ? never : Type
|
|
2335
|
+
: never;
|
|
1325
2336
|
|
|
1326
|
-
|
|
1327
|
-
//=> boolean
|
|
1328
|
-
```
|
|
2337
|
+
// For `@link`
|
|
1329
2338
|
|
|
1330
|
-
|
|
2339
|
+
/**
|
|
2340
|
+
Merge two types into a new type. Keys of the second type override keys of the first type.
|
|
2341
|
+
|
|
2342
|
+
This is different from the TypeScript `&` (intersection) operator. With `&`, conflicting property types are intersected, which often results in `never`. For example, `{a: string} & {a: number}` makes `a` become `string & number`, which resolves to `never`. With `Merge`, the second type's keys cleanly override the first, so `Merge<{a: string}, {a: number}>` gives `{a: number}` as expected. `Merge` also produces a flattened type (via `Simplify`), making it more readable in IDE tooltips compared to `A & B`.
|
|
1331
2343
|
|
|
1332
2344
|
@example
|
|
1333
2345
|
```
|
|
1334
|
-
import type {
|
|
1335
|
-
|
|
1336
|
-
type A = Or<true, never>;
|
|
1337
|
-
//=> true
|
|
1338
|
-
|
|
1339
|
-
type B = Or<never, true>;
|
|
1340
|
-
//=> true
|
|
1341
|
-
|
|
1342
|
-
type C = Or<false, never>;
|
|
1343
|
-
//=> false
|
|
2346
|
+
import type {Merge} from 'type-fest';
|
|
1344
2347
|
|
|
1345
|
-
type
|
|
1346
|
-
|
|
2348
|
+
type Foo = {
|
|
2349
|
+
a: string;
|
|
2350
|
+
b: number;
|
|
2351
|
+
};
|
|
1347
2352
|
|
|
1348
|
-
type
|
|
1349
|
-
|
|
2353
|
+
type Bar = {
|
|
2354
|
+
a: number; // Conflicts with Foo['a']
|
|
2355
|
+
c: boolean;
|
|
2356
|
+
};
|
|
1350
2357
|
|
|
1351
|
-
|
|
1352
|
-
|
|
2358
|
+
// With `&`, `a` becomes `string & number` which is `never`. Not what you want.
|
|
2359
|
+
type WithIntersection = (Foo & Bar)['a'];
|
|
2360
|
+
//=> never
|
|
1353
2361
|
|
|
1354
|
-
|
|
1355
|
-
|
|
2362
|
+
// With `Merge`, `a` is cleanly overridden to `number`.
|
|
2363
|
+
type WithMerge = Merge<Foo, Bar>['a'];
|
|
2364
|
+
//=> number
|
|
1356
2365
|
```
|
|
1357
2366
|
|
|
1358
|
-
@
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
*/
|
|
1362
|
-
type Or<A extends boolean, B extends boolean> = OrAll<[A, B]>;
|
|
1363
|
-
|
|
1364
|
-
/**
|
|
1365
|
-
@see {@link AllExtend}
|
|
1366
|
-
*/
|
|
1367
|
-
type AllExtendOptions = {
|
|
1368
|
-
/**
|
|
1369
|
-
Consider `never` elements to match the target type only if the target type itself is `never` (or `any`).
|
|
2367
|
+
@example
|
|
2368
|
+
```
|
|
2369
|
+
import type {Merge} from 'type-fest';
|
|
1370
2370
|
|
|
1371
|
-
|
|
1372
|
-
|
|
2371
|
+
type Foo = {
|
|
2372
|
+
[x: string]: unknown;
|
|
2373
|
+
[x: number]: unknown;
|
|
2374
|
+
foo: string;
|
|
2375
|
+
bar: symbol;
|
|
2376
|
+
};
|
|
1373
2377
|
|
|
1374
|
-
|
|
2378
|
+
type Bar = {
|
|
2379
|
+
[x: number]: number;
|
|
2380
|
+
[x: symbol]: unknown;
|
|
2381
|
+
bar: Date;
|
|
2382
|
+
baz: boolean;
|
|
2383
|
+
};
|
|
1375
2384
|
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
2385
|
+
export type FooBar = Merge<Foo, Bar>;
|
|
2386
|
+
//=> {
|
|
2387
|
+
// [x: string]: unknown;
|
|
2388
|
+
// [x: number]: number;
|
|
2389
|
+
// [x: symbol]: unknown;
|
|
2390
|
+
// foo: string;
|
|
2391
|
+
// bar: Date;
|
|
2392
|
+
// baz: boolean;
|
|
2393
|
+
// }
|
|
2394
|
+
```
|
|
1379
2395
|
|
|
1380
|
-
|
|
1381
|
-
//=> false
|
|
2396
|
+
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.
|
|
1382
2397
|
|
|
1383
|
-
|
|
1384
|
-
//=> true
|
|
2398
|
+
Use {@link MergeAll} to merge more than two types.
|
|
1385
2399
|
|
|
1386
|
-
|
|
1387
|
-
//=> true
|
|
2400
|
+
Use {@link Modify} to also remove keys: a key of the source with the `never` type removes that key from the result.
|
|
1388
2401
|
|
|
1389
|
-
|
|
1390
|
-
//=> true
|
|
2402
|
+
Two tuples are combined position by position, so `Merge<[1, 2, 3], [4, 5]>` is `[4, 5, 3]`. Use {@link Spread} to append them instead.
|
|
1391
2403
|
|
|
1392
|
-
|
|
1393
|
-
//=> true
|
|
2404
|
+
A call signature is kept: the source's if it has one, otherwise the destination's.
|
|
1394
2405
|
|
|
1395
|
-
|
|
1396
|
-
//=> true
|
|
2406
|
+
Numeric keys and their string forms name the same property, so `Merge<{0: string}, {'0': number}>` is `{'0': number}`.
|
|
1397
2407
|
|
|
1398
|
-
|
|
1399
|
-
|
|
2408
|
+
Known limitations:
|
|
2409
|
+
- Inside a generic function, a value such as `{...a, ...b}` (typed as `A & B`) is not assignable to `Merge<A, B>`, because TypeScript cannot resolve `Merge` until `A` and `B` are known. Use a type assertion: `{...a, ...b} as unknown as Merge<A, B>`.
|
|
2410
|
+
- The kept call signature is rebuilt, so an overloaded function keeps only its last signature, a generic function loses its type parameters, and a type predicate becomes `boolean`. A construct signature is dropped.
|
|
1400
2411
|
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
2412
|
+
@see {@link ObjectMerge}
|
|
2413
|
+
@see {@link MergeAll}
|
|
2414
|
+
@category Object
|
|
2415
|
+
*/
|
|
2416
|
+
type Merge<Destination, Source> =
|
|
2417
|
+
Destination extends unknown // For distributing `Destination`
|
|
2418
|
+
? Source extends unknown // For distributing `Source`
|
|
2419
|
+
? If<
|
|
2420
|
+
IsEqual<Destination, Source>,
|
|
2421
|
+
Destination,
|
|
2422
|
+
// Two arrays or tuples are combined position by position, see `CombineTwoArrays`.
|
|
2423
|
+
Destination extends readonly unknown[]
|
|
2424
|
+
? Source extends readonly unknown[]
|
|
2425
|
+
// `any` takes both branches of an array check, so the array branch is dropped when either side is `any` to leave just the object merge. A union with `any` is `any`, so this checks both sides at once.
|
|
2426
|
+
? IsAny<Destination | Source> extends true
|
|
2427
|
+
? never
|
|
2428
|
+
: CombineTwoArrays<Destination, Source>
|
|
2429
|
+
: _Merge<Destination, Source>
|
|
2430
|
+
: _Merge<Destination, Source>
|
|
2431
|
+
>
|
|
2432
|
+
: never // Should never happen
|
|
2433
|
+
: never; // Should never happen
|
|
1407
2434
|
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
2435
|
+
/**
|
|
2436
|
+
Combines two arrays position by position: the source's elements override the destination's, and the destination's positions past the source are kept, so `Merge<[1, 2, 3], [4, 5]>` is `[4, 5, 3]`. An array of unknown length has no positions to override, so the result is an array of both element types.
|
|
2437
|
+
|
|
2438
|
+
Note that this is not what either built-in spread does. The array spread of `[1, 2, 3]` and `[4, 5]` appends, giving `[1, 2, 3, 4, 5]`, and the object spread of the two gives a plain object `{0: 4, 1: 5, 2: 3}` with no `length`. This follows {@link Merge}'s own rule that the source's keys override the destination's keys, applied to the index keys a tuple has. Use {@link Spread} instead when the array spread is what you want.
|
|
2439
|
+
*/
|
|
2440
|
+
type CombineTwoArrays<Destination extends readonly unknown[], Source extends readonly unknown[]> =
|
|
2441
|
+
// A source with an optional element has no fixed positions to override, so it is treated like an array of unknown length.
|
|
2442
|
+
number extends Destination['length'] | Source['length'] | (Source extends Required<Source> ? never : number)
|
|
2443
|
+
? IsReadonlyArray<Destination> extends true
|
|
2444
|
+
? IsReadonlyArray<Source> extends true
|
|
2445
|
+
? ReadonlyArray<Destination[number] | Source[number]>
|
|
2446
|
+
: Array<Destination[number] | Source[number]>
|
|
2447
|
+
: Array<Destination[number] | Source[number]>
|
|
2448
|
+
: IsReadonlyArray<Destination> extends true
|
|
2449
|
+
? IsReadonlyArray<Source> extends true
|
|
2450
|
+
? readonly [...Source, ...DropLeading<Destination, Source['length']>]
|
|
2451
|
+
: [...Source, ...DropLeading<Destination, Source['length']>]
|
|
2452
|
+
: [...Source, ...DropLeading<Destination, Source['length']>];
|
|
1411
2453
|
|
|
1412
2454
|
/**
|
|
1413
|
-
|
|
2455
|
+
The elements of an array once the given number of leading ones is removed. An optional element counts as a position too.
|
|
2456
|
+
*/
|
|
2457
|
+
type DropLeading<Array extends readonly unknown[], Length extends number, Dropped extends unknown[] = []> =
|
|
2458
|
+
Dropped['length'] extends Length
|
|
2459
|
+
? Array
|
|
2460
|
+
: Array extends readonly []
|
|
2461
|
+
? []
|
|
2462
|
+
: Array extends readonly [unknown?, ...infer Rest]
|
|
2463
|
+
? DropLeading<Rest, Length, [...Dropped, unknown]>
|
|
2464
|
+
: [];
|
|
1414
2465
|
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
2466
|
+
type _Merge<Destination, Source> =
|
|
2467
|
+
// The mapped types in `MergeObjects` drop call signatures, so the source's call signature, or else the destination's, is added back. Each branch has its own intersection, so that tooltips show the result rather than `_Merge`.
|
|
2468
|
+
unknown extends CallSignatureOf<Source>
|
|
2469
|
+
? CallSignatureOf<Destination> & MergeObjects<Destination, Source>
|
|
2470
|
+
: CallSignatureOf<Source> & MergeObjects<Destination, Source>;
|
|
2471
|
+
|
|
2472
|
+
// Numeric properties, enum keys, and their string forms name the same property, so normalize the source's named keys before testing overrides.
|
|
2473
|
+
// Merges the properties and index signatures of two objects. A key of the destination is dropped when the source overrides it: an index signature only by an index signature, and a property only by a property. The destination is read only once, because each extra read multiplies the work of nested merges, such as in `MergeAll`. The source is rebuilt with key remapping instead of intersected as is, because an intersection with an `any` source is `any`, which loses the properties of the destination.
|
|
2474
|
+
type MergeObjects<Destination, Source> = SimplifyObject<{
|
|
2475
|
+
[Key in keyof Destination as {} extends Record<Key, never>
|
|
2476
|
+
? Key extends keyof PickIndexSignature<Source> ? never : Key
|
|
2477
|
+
: Key extends KeyAliases<keyof OmitIndexSignature<Source>> ? never : Key
|
|
2478
|
+
]: Destination[Key];
|
|
2479
|
+
} & {[Key in keyof Source as Key]: Source[Key]}>;
|
|
2480
|
+
|
|
2481
|
+
// For `@link`
|
|
1418
2482
|
|
|
1419
|
-
|
|
1420
|
-
|
|
2483
|
+
/**
|
|
2484
|
+
Apply default options to specified options, preserving literal types.
|
|
1421
2485
|
|
|
1422
|
-
type
|
|
1423
|
-
//=> false
|
|
2486
|
+
Useful for authors of configurable utility types. `Defaults` must give every optional option a default and must not give a default for a required option. Each default must be assignable to its option type. `SpecifiedOptions` must satisfy `Options`, including its required properties. Use {@link DefaultsFor} to define a defaults object.
|
|
1424
2487
|
|
|
1425
|
-
|
|
1426
|
-
//=> boolean
|
|
2488
|
+
The resolution is shallow, so a nested object is replaced as a whole. A specified option overrides its default. An optional or `undefined`-including specified option uses the default when the declared type does not admit `undefined`, and still overrides when the declared type admits `undefined`, such as `unknown` or `string | undefined`. A numeric key can use either spelling, so `0` and `'0'` name the same option. Every option declared in `Options` is required, and its `readonly` modifier comes from the chosen default or override.
|
|
1427
2489
|
|
|
1428
|
-
|
|
1429
|
-
//=> boolean
|
|
2490
|
+
@example
|
|
1430
2491
|
```
|
|
2492
|
+
import type {ApplyDefaultOptions} from 'type-fest';
|
|
1431
2493
|
|
|
1432
|
-
|
|
2494
|
+
type FormatOptions = {
|
|
2495
|
+
uppercase?: boolean;
|
|
2496
|
+
prefix?: string;
|
|
2497
|
+
};
|
|
1433
2498
|
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
2499
|
+
type DefaultFormatOptions = {
|
|
2500
|
+
uppercase: false;
|
|
2501
|
+
prefix: '';
|
|
2502
|
+
};
|
|
1437
2503
|
|
|
1438
|
-
type
|
|
1439
|
-
//=> true
|
|
1440
|
-
```
|
|
2504
|
+
type Format<Value extends string, Options extends FormatOptions = {}> = FormatWithOptions<Value, ApplyDefaultOptions<FormatOptions, DefaultFormatOptions, Options>>;
|
|
1441
2505
|
|
|
1442
|
-
|
|
1443
|
-
// @exactOptionalPropertyTypes: false
|
|
1444
|
-
import type {AllExtend} from 'type-fest';
|
|
2506
|
+
type FormatWithOptions<Value extends string, Options extends Required<FormatOptions>> = `${Options['prefix']}${Options['uppercase'] extends true ? Uppercase<Value> : Value}`;
|
|
1445
2507
|
|
|
1446
|
-
type
|
|
1447
|
-
//=>
|
|
2508
|
+
type Plain = Format<'hello'>;
|
|
2509
|
+
//=> 'hello'
|
|
1448
2510
|
|
|
1449
|
-
type
|
|
1450
|
-
//=>
|
|
2511
|
+
type Heading = Format<'hello', {uppercase: true; prefix: '# '}>;
|
|
2512
|
+
//=> '# HELLO'
|
|
2513
|
+
|
|
2514
|
+
type Resolved = ApplyDefaultOptions<FormatOptions, DefaultFormatOptions, {uppercase?: true}>;
|
|
2515
|
+
//=> {uppercase: false; prefix: ''}
|
|
1451
2516
|
```
|
|
1452
2517
|
|
|
1453
|
-
|
|
2518
|
+
Known limitations:
|
|
2519
|
+
- Intended for an object with named properties. Arrays, tuples, and functions are not supported. A string index signature on `Options` blocks defaults for its named options.
|
|
2520
|
+
- A union of option types or a union-valued option uses one resolution, usually the defaults. A `never` option value is not supported.
|
|
2521
|
+
- Extra properties are allowed: an extra specified property is kept unless it can be `undefined`, and extra `Defaults` keys are kept.
|
|
2522
|
+
- With `any` or `never` as `SpecifiedOptions`, the defaults are used, or `never` if `Options` has a required property.
|
|
2523
|
+
- This does not model runtime object spread, so TypeScript may require concrete specified options instead of unresolved generics.
|
|
1454
2524
|
|
|
1455
|
-
@
|
|
1456
|
-
@category
|
|
2525
|
+
@see {@link DefaultsFor}
|
|
2526
|
+
@category Object
|
|
1457
2527
|
*/
|
|
1458
|
-
type
|
|
1459
|
-
|
|
2528
|
+
type ApplyDefaultOptions<
|
|
2529
|
+
Options extends object,
|
|
2530
|
+
Defaults extends SimplifyObject<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
|
|
2531
|
+
SpecifiedOptions extends Options,
|
|
2532
|
+
> =
|
|
2533
|
+
// Keep the resolved type assignable to `Required<Options>` without inferring a result that can widen a specified generic value to its constraint.
|
|
2534
|
+
_ApplyDefaultOptions<Options, Defaults, SpecifiedOptions> extends Required<Options>
|
|
2535
|
+
? _ApplyDefaultOptions<Options, Defaults, SpecifiedOptions>
|
|
2536
|
+
: never;
|
|
2537
|
+
|
|
2538
|
+
type _ApplyDefaultOptions<
|
|
2539
|
+
Options extends object,
|
|
2540
|
+
Defaults,
|
|
2541
|
+
SpecifiedOptions,
|
|
2542
|
+
> =
|
|
2543
|
+
If<IsAny<SpecifiedOptions>, Defaults,
|
|
2544
|
+
If<IsNever<SpecifiedOptions>, Defaults,
|
|
2545
|
+
// The overrides are already an object map, so skip `Merge`'s array and equality dispatch.
|
|
2546
|
+
_Merge<Defaults, {
|
|
2547
|
+
// The first `as` branch keeps the key of an option whose declared type admits `undefined`, like `unknown`, because `undefined` is one of its valid values. `-?` then strips the optional modifier, so an unnarrowed options type still resolves instead of failing the `Required<Options>` guard above.
|
|
2548
|
+
[Key in keyof SpecifiedOptions
|
|
2549
|
+
as undefined extends Required<Options>[MatchingKey<Options, Key>] ? Key : undefined extends SpecifiedOptions[Key] ? never : Key
|
|
2550
|
+
]-?: SpecifiedOptions[Key]
|
|
2551
|
+
}>>>;
|
|
1460
2552
|
|
|
1461
|
-
|
|
1462
|
-
TArray extends readonly [infer First, ...infer Rest]
|
|
1463
|
-
? IsNever<First> extends true
|
|
1464
|
-
? Or<Or<IsNever<Type>, IsAny<Type>>, Not<Options['strictNever']>> extends true
|
|
1465
|
-
// If target `Type` is also `never`, or is `any`, or `strictNever` is disabled, recurse further.
|
|
1466
|
-
? _AllExtend<Rest, Type, Options>
|
|
1467
|
-
: false
|
|
1468
|
-
: First extends Type
|
|
1469
|
-
? _AllExtend<Rest, Type, Options>
|
|
1470
|
-
: false
|
|
1471
|
-
: true,
|
|
1472
|
-
false, false>;
|
|
2553
|
+
// For `@link`
|
|
1473
2554
|
|
|
1474
2555
|
/**
|
|
1475
|
-
|
|
2556
|
+
Returns a boolean for whether the two given types are equal.
|
|
1476
2557
|
|
|
1477
|
-
|
|
1478
|
-
Returns `never` if `Key` extends `Exclude`.
|
|
1479
|
-
Returns `Key` otherwise.
|
|
2558
|
+
Compares unions as a whole. Special types such as `any`, `never`, and `unknown` are compared by identity rather than assignability.
|
|
1480
2559
|
|
|
1481
|
-
@
|
|
1482
|
-
|
|
1483
|
-
type Filtered = Filter<'foo', 'foo'>;
|
|
1484
|
-
//=> never
|
|
1485
|
-
```
|
|
2560
|
+
@see https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
|
|
2561
|
+
@see https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
|
|
1486
2562
|
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
type Filtered = Filter<'bar', string>;
|
|
1490
|
-
//=> never
|
|
1491
|
-
```
|
|
2563
|
+
Use-cases:
|
|
2564
|
+
- If you want to make a conditional branch based on the result of a comparison of two types.
|
|
1492
2565
|
|
|
1493
2566
|
@example
|
|
1494
2567
|
```
|
|
1495
|
-
type
|
|
1496
|
-
//=> 'bar'
|
|
1497
|
-
```
|
|
2568
|
+
import type {IsEqual} from 'type-fest';
|
|
1498
2569
|
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
type
|
|
2570
|
+
// This type returns a boolean for whether the given array includes the given item.
|
|
2571
|
+
// `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
|
|
2572
|
+
type Includes<Value extends readonly any[], Item> =
|
|
2573
|
+
Value extends readonly [Value[0], ...infer rest]
|
|
2574
|
+
? IsEqual<Value[0], Item> extends true
|
|
2575
|
+
? true
|
|
2576
|
+
: Includes<rest, Item>
|
|
2577
|
+
: false;
|
|
2578
|
+
```
|
|
1502
2579
|
|
|
1503
|
-
type
|
|
1504
|
-
/**
|
|
1505
|
-
Disallow assigning non-specified properties.
|
|
2580
|
+
Note: An intersection of object types is not equal to the same type written as one object, so `IsEqual<{a: 0} & {b: 0}, {a: 0; b: 0}>` is `false`. Wrap both types in `Simplify`, or `SimplifyDeep` for nested intersections, to compare them as plain objects.
|
|
1506
2581
|
|
|
1507
|
-
|
|
2582
|
+
Note: Use {@link IsMutuallyAssignable} when you only need each type assignable to the other. It is weaker (it ignores `readonly` on properties) and cheaper.
|
|
1508
2583
|
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
2584
|
+
@category Type Guard
|
|
2585
|
+
@category Utilities
|
|
2586
|
+
*/
|
|
2587
|
+
type IsEqual<A, B> =
|
|
2588
|
+
[A] extends [B]
|
|
2589
|
+
? [B] extends [A]
|
|
2590
|
+
? _IsEqual<A, B>
|
|
2591
|
+
: false
|
|
2592
|
+
: false;
|
|
1513
2593
|
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
2594
|
+
/*
|
|
2595
|
+
`IsEqual` above repeats the assignability check from `IsMutuallyAssignable` instead of calling it, because delegating fails the generic constraint in the `Assignability` test in `test-d/is-equal.ts` (issue #1305).
|
|
2596
|
+
*/
|
|
1517
2597
|
|
|
1518
|
-
|
|
1519
|
-
|
|
2598
|
+
// This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`.
|
|
2599
|
+
type _IsEqual<A, B> =
|
|
2600
|
+
(<G>() => G extends A & G | G ? 1 : 2) extends
|
|
2601
|
+
(<G>() => G extends B & G | G ? 1 : 2)
|
|
2602
|
+
? true
|
|
2603
|
+
: false;
|
|
1520
2604
|
|
|
1521
|
-
|
|
2605
|
+
// For `@link`
|
|
1522
2606
|
|
|
1523
|
-
|
|
2607
|
+
/**
|
|
2608
|
+
Extract all readonly keys from the given type.
|
|
1524
2609
|
|
|
1525
|
-
|
|
2610
|
+
Use {@link PickReadonly} to create a type that contains the readonly properties only.
|
|
1526
2611
|
|
|
1527
2612
|
@example
|
|
1528
2613
|
```
|
|
1529
|
-
import type {
|
|
1530
|
-
|
|
1531
|
-
type Foo = {
|
|
1532
|
-
a: number;
|
|
1533
|
-
b: string;
|
|
1534
|
-
};
|
|
2614
|
+
import type {ReadonlyKeysOf} from 'type-fest';
|
|
1535
2615
|
|
|
1536
|
-
type
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
// @ts-expect-error
|
|
1540
|
-
const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
|
|
1541
|
-
// errors: 'a' does not exist in type '{ b: string; }'
|
|
2616
|
+
type User = {
|
|
2617
|
+
name: string;
|
|
2618
|
+
surname: string;
|
|
1542
2619
|
|
|
1543
|
-
|
|
1544
|
-
|
|
2620
|
+
readonly id: number;
|
|
2621
|
+
};
|
|
1545
2622
|
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
2623
|
+
type UserReadonlyKeys = ReadonlyKeysOf<User>;
|
|
2624
|
+
//=> 'id'
|
|
2625
|
+
```
|
|
1549
2626
|
|
|
1550
|
-
|
|
2627
|
+
Extract all readonly keys from a union of object types.
|
|
1551
2628
|
|
|
1552
|
-
|
|
2629
|
+
@example
|
|
2630
|
+
```
|
|
2631
|
+
import type {ReadonlyKeysOf} from 'type-fest';
|
|
1553
2632
|
|
|
1554
|
-
type
|
|
1555
|
-
|
|
1556
|
-
email: string;
|
|
2633
|
+
type User = {
|
|
2634
|
+
readonly id: string;
|
|
1557
2635
|
name: string;
|
|
1558
|
-
role: 'admin' | 'user';
|
|
1559
2636
|
};
|
|
1560
2637
|
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2638
|
+
type Post = {
|
|
2639
|
+
readonly id: string;
|
|
2640
|
+
readonly author: string;
|
|
2641
|
+
body: string;
|
|
2642
|
+
};
|
|
1564
2643
|
|
|
1565
|
-
|
|
1566
|
-
//
|
|
1567
|
-
type PostPayloadFixed = Except<UserData, 'email'>;
|
|
1568
|
-
//=> {[x: string]: string; name: string; role: 'admin' | 'user'}
|
|
2644
|
+
type ReadonlyKeys = ReadonlyKeysOf<User | Post>;
|
|
2645
|
+
// The readonly keys are 'id' and 'author'.
|
|
1569
2646
|
```
|
|
1570
2647
|
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {}> =
|
|
1574
|
-
_Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>;
|
|
2648
|
+
Known limitations:
|
|
2649
|
+
- A union reports the keys of each of its members, so the result can name a key that is not a key of the union itself. `keyof` of a union is the intersection of its members' keys, so `ReadonlyKeysOf<{readonly a?: string} | {readonly b?: number}>` is `'a' | 'b'` while `keyof` of the same union is `never`. Read one member at a time if you need a key that is valid for the whole union.
|
|
1575
2650
|
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
2651
|
+
@category Utilities
|
|
2652
|
+
*/
|
|
2653
|
+
type ReadonlyKeysOf<Type extends object> =
|
|
2654
|
+
// Check `any` once; each mapped key already belongs to its distributed member.
|
|
2655
|
+
IsAny<Type> extends true ? never
|
|
2656
|
+
: Type extends unknown // For distributing `Type`
|
|
2657
|
+
? (keyof {[Key in keyof Type as
|
|
2658
|
+
IsReadonlyProperty<Type, Key> extends true ? Key : never
|
|
2659
|
+
]: never
|
|
2660
|
+
}) & keyof Type // Intersect with `keyof Type` to narrow the member's own keys. For a union this runs per member, see the note on unions in the docs.
|
|
2661
|
+
: never; // Should never happen
|
|
1581
2662
|
|
|
1582
2663
|
/**
|
|
1583
|
-
Create a type that makes the given keys required
|
|
2664
|
+
Create a type that makes the given keys required, while keeping the remaining keys as is.
|
|
1584
2665
|
|
|
1585
2666
|
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.
|
|
1586
2667
|
|
|
2668
|
+
Note: This only removes the optional modifier, the same as the built-in `Required`. It does not remove `undefined` from the value type of a non-optional key, so `SetRequired<{a: number | undefined}, 'a'>` is `{a: number | undefined}`. Use `SetNonNullable` to remove `null` and `undefined` from the value type.
|
|
2669
|
+
|
|
1587
2670
|
@example
|
|
1588
2671
|
```
|
|
1589
2672
|
import type {SetRequired} from 'type-fest';
|
|
@@ -1602,25 +2685,63 @@ type ArrayExample = SetRequired<[number?, number?, number?], 0 | 1>;
|
|
|
1602
2685
|
//=> [number, number, number?]
|
|
1603
2686
|
```
|
|
1604
2687
|
|
|
2688
|
+
@example
|
|
2689
|
+
```
|
|
2690
|
+
import type {SetRequired} from 'type-fest';
|
|
2691
|
+
|
|
2692
|
+
type Options = {
|
|
2693
|
+
timeout?: number;
|
|
2694
|
+
retries?: number;
|
|
2695
|
+
cwd?: string;
|
|
2696
|
+
};
|
|
2697
|
+
|
|
2698
|
+
// Require exactly the keys that a given object provides, keeping the value types of `Options`.
|
|
2699
|
+
// For example, a partially built options object that is still mutated afterwards.
|
|
2700
|
+
const partial = {
|
|
2701
|
+
timeout: 1000,
|
|
2702
|
+
cwd: '/',
|
|
2703
|
+
} satisfies Partial<Options>;
|
|
2704
|
+
|
|
2705
|
+
const options: SetRequired<Options, keyof typeof partial> = partial;
|
|
2706
|
+
//=> {retries?: number; timeout: number; cwd: string}
|
|
2707
|
+
```
|
|
2708
|
+
|
|
2709
|
+
Known limitations:
|
|
2710
|
+
- A key that lands after an optional element of a tuple is ignored. TypeScript rejects a required element that follows an optional one, so `[number?, number]` is not a tuple type, and the walk stops at the first optional element. `SetRequired<[number?, number?], 1>` is `[number?, number?]`, while naming both keys gives `[number, number]`. `SetRequiredDeep` answers the same way for a path that lands on such a key.
|
|
2711
|
+
- A key that lands in a rest element is ignored, because a rest element has no optionality to remove: its elements are always present, and the `undefined` in a rest element of `Array<number | undefined>` is a value the element may hold rather than the element being absent. `SetRequired<[string, number?], 1>` is `[string, number]` because there the `?` is real optionality. `SetNonNullable` does make a rest element non-nullable, because that is a change to the value rather than to the optionality.
|
|
2712
|
+
- Index keys are not supported on an array with extra members, such as a `Tagged` tuple, because the tuple is rebuilt from its elements. On an array, only index keys are supported, or only other keys. Other keys, such as `length`, make the result an object type.
|
|
2713
|
+
- The result for a class with `private`, `protected`, or `#private` members is not assignable to the class, because `keyof` does not include these members. The built-in `Required` has the same limitation. Use `ClassType & SetRequired<ClassType, Keys>` to keep them.
|
|
2714
|
+
|
|
1605
2715
|
@category Object
|
|
1606
2716
|
*/
|
|
1607
|
-
type SetRequired<BaseType, Keys extends
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
2717
|
+
type SetRequired<BaseType, Keys extends KeysOfUnion<BaseType>> =
|
|
2718
|
+
// The call signature is rebuilt per member, so a union of callables does not mix their signatures.
|
|
2719
|
+
BaseType extends unknown
|
|
2720
|
+
? CallSignatureOf<BaseType> & _SetRequired<BaseType, UnwrapPathBrand<Keys>>
|
|
2721
|
+
: never;
|
|
1612
2722
|
|
|
1613
|
-
type _SetRequired<BaseType, Keys
|
|
2723
|
+
type _SetRequired<BaseType, Keys> =
|
|
1614
2724
|
BaseType extends UnknownArray
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
2725
|
+
// `any` takes both branches of the array check, so its array branch is dropped to leave just the object branch.
|
|
2726
|
+
? IsAny<BaseType> extends true
|
|
2727
|
+
? never
|
|
2728
|
+
// Returned as is, since rebuilding the array would drop non-index members, such as the tag of a `Tagged` array.
|
|
2729
|
+
: IsNever<Keys> extends true
|
|
2730
|
+
? BaseType
|
|
2731
|
+
// Only index keys are handled as tuple elements. Other keys, such as an extra property of an augmented array, take the object branch.
|
|
2732
|
+
: [Keys] extends [number | `${number}`]
|
|
2733
|
+
? IsReadonlyArray<BaseType> extends true
|
|
2734
|
+
? Readonly<SetArrayRequired<BaseType, Keys>>
|
|
2735
|
+
: SetArrayRequired<BaseType, Keys>
|
|
2736
|
+
: _SetObjectRequired<BaseType, SelectedKeys<BaseType, Keys>>
|
|
2737
|
+
: _SetObjectRequired<BaseType, SelectedKeys<BaseType, Keys>>;
|
|
2738
|
+
|
|
2739
|
+
type _SetObjectRequired<BaseType, Keys extends keyof BaseType> = SimplifyObject<
|
|
2740
|
+
// Pick just the keys that are not made required from the base type.
|
|
2741
|
+
{[Key in keyof BaseType as Key extends Keys ? never : Key]: BaseType[Key]}
|
|
2742
|
+
// Pick the keys that should be required from the base type and make them required.
|
|
2743
|
+
& {[Key in keyof BaseType as Key extends Keys ? Key : never]-?: BaseType[Key]}
|
|
2744
|
+
>;
|
|
1624
2745
|
|
|
1625
2746
|
/**
|
|
1626
2747
|
Remove the optional modifier from the specified keys in an array.
|
|
@@ -1631,27 +2752,33 @@ type SetArrayRequired<
|
|
|
1631
2752
|
Counter extends any[] = [],
|
|
1632
2753
|
Accumulator extends UnknownArray = [],
|
|
1633
2754
|
> = TArray extends unknown // For distributing `TArray` when it's a union
|
|
1634
|
-
? keyof TArray
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
2755
|
+
? '0' extends keyof TArray
|
|
2756
|
+
? TArray extends readonly [(infer First)?, ...infer Rest]
|
|
2757
|
+
// A tuple allows fewer than one element only when its first element is optional. Written in exactly this shape because equivalent ones, such as `[] extends TArray`, are several times slower.
|
|
2758
|
+
// Unlike the other array loops, this one has no `any` guard above it, so the check is wrapped in tuples to stop `any` from matching both branches.
|
|
2759
|
+
? [TArray] extends [readonly [unknown, ...unknown[]]]
|
|
2760
|
+
? SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, First]>
|
|
2761
|
+
: `${Counter['length']}` extends `${Keys & (string | number)}` // If the current index needs to be required
|
|
1641
2762
|
? SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, First]>
|
|
1642
2763
|
// If the current element is optional, but it doesn't need to be required,
|
|
1643
2764
|
// then we can exit early, since no further elements can now be made required.
|
|
1644
2765
|
: [...Accumulator, ...TArray]
|
|
1645
|
-
: SetArrayRequired<Rest, Keys, [...Counter, any], [...Accumulator, TArray[0]]>
|
|
1646
2766
|
: never // Should never happen, since `[(infer F)?, ...infer R]` is a top-type for arrays.
|
|
2767
|
+
// Exit if `TArray` is empty (e.g., []), or
|
|
2768
|
+
// `TArray` contains no non-rest elements preceding the rest element (e.g., `[...string[]]` or `[...string[], string]`).
|
|
2769
|
+
: [...Accumulator, ...TArray]
|
|
1647
2770
|
: never; // Should never happen
|
|
1648
2771
|
|
|
2772
|
+
// For `@link`
|
|
2773
|
+
|
|
1649
2774
|
type SetFieldTypeOptions = {
|
|
1650
2775
|
/**
|
|
1651
2776
|
Preserve optional and readonly modifiers for properties being updated.
|
|
1652
2777
|
|
|
1653
2778
|
NOTE: Property modifiers will always be preserved for properties that are not being updated.
|
|
1654
2779
|
|
|
2780
|
+
Known limitation: A numeric key that is selected in the other spelling (`'0'` for a key declared as `0`, or the reverse) gets the new type, but keeps its modifiers.
|
|
2781
|
+
|
|
1655
2782
|
@default true
|
|
1656
2783
|
*/
|
|
1657
2784
|
preservePropertyModifiers?: boolean;
|
|
@@ -1670,6 +2797,10 @@ Use-cases:
|
|
|
1670
2797
|
|
|
1671
2798
|
@see `Merge` if you need to change multiple properties to different types.
|
|
1672
2799
|
|
|
2800
|
+
This type only changes the type of the given keys at the top level. For a deeply nested property, use {@link SetProperty} with a key path: `SetProperty<{a: {b: string}}, 'a.b', number>` is `{a: {b: number}}`.
|
|
2801
|
+
|
|
2802
|
+
@see {@link SetProperty}
|
|
2803
|
+
|
|
1673
2804
|
@example
|
|
1674
2805
|
```
|
|
1675
2806
|
import type {SetFieldType} from 'type-fest';
|
|
@@ -1698,16 +2829,30 @@ type MyModelApi2 = SetFieldType<MyModel, 'createdAt' | 'updatedAt', string, {pre
|
|
|
1698
2829
|
|
|
1699
2830
|
@category Object
|
|
1700
2831
|
*/
|
|
1701
|
-
type SetFieldType<BaseType, Keys extends
|
|
1702
|
-
_SetFieldType<BaseType, Keys
|
|
2832
|
+
type SetFieldType<BaseType, Keys extends KeysOfUnion<BaseType>, NewType, Options extends SetFieldTypeOptions = {}> =
|
|
2833
|
+
_SetFieldType<BaseType, KeySelector<UnwrapPathBrand<Keys>>, NewType, ApplyDefaultOptions<SetFieldTypeOptions, DefaultSetFieldTypeOptions, Options>>;
|
|
2834
|
+
|
|
2835
|
+
type _SetFieldType<BaseType, Keys, NewType, Options extends Required<SetFieldTypeOptions>> =
|
|
2836
|
+
// The distribution comes first, so that a member the keys do not reach is left as it is. Otherwise the `Record` below hands it a key it never had, as a required one when the modifiers are not preserved.
|
|
2837
|
+
BaseType extends unknown
|
|
2838
|
+
? SimplifyObject<{
|
|
2839
|
+
// Tuple elements use string indices, so look up their canonical numeric aliases in the selector, which matches each union member by its own spelling. Other numeric-looking names, like '01', stay distinct.
|
|
2840
|
+
[P in keyof BaseType]: P extends SelectedKeys<BaseType, Keys>
|
|
2841
|
+
? NewType
|
|
2842
|
+
: [SelectedKeyAlias<Keys, P>] extends [never]
|
|
2843
|
+
? BaseType[P]
|
|
2844
|
+
: NewType;
|
|
2845
|
+
} & (
|
|
2846
|
+
// `Record` is used to remove property modifiers. Matching declared spellings are added without replacing the original selector, so autocomplete unions retain their known required members beside index signatures. A tuple is left out of it: `Record` over `number` answers with every member an array has, which is not a tuple.
|
|
2847
|
+
Options['preservePropertyModifiers'] extends false
|
|
2848
|
+
? BaseType extends readonly unknown[]
|
|
2849
|
+
? unknown
|
|
2850
|
+
: Record<SelectedKeys<BaseType, Keys> & PropertyKey, NewType>
|
|
2851
|
+
: unknown
|
|
2852
|
+
)>
|
|
2853
|
+
: never; // Should never happen
|
|
1703
2854
|
|
|
1704
|
-
|
|
1705
|
-
Simplify<{
|
|
1706
|
-
[P in keyof BaseType]: P extends Keys ? NewType : BaseType[P];
|
|
1707
|
-
} & (
|
|
1708
|
-
// `Record` is used to remove property modifiers
|
|
1709
|
-
Options['preservePropertyModifiers'] extends false ? Record<Keys, NewType> : unknown
|
|
1710
|
-
)>;
|
|
2855
|
+
// For `@link`
|
|
1711
2856
|
|
|
1712
2857
|
/**
|
|
1713
2858
|
Create a type with shared fields from a union of object types.
|
|
@@ -1732,6 +2877,9 @@ type Dog = {
|
|
|
1732
2877
|
dogType: string;
|
|
1733
2878
|
};
|
|
1734
2879
|
|
|
2880
|
+
type PetInfo = SharedUnionFields<Cat | Dog>;
|
|
2881
|
+
//=> {name: string; type: 'cat' | 'dog'}
|
|
2882
|
+
|
|
1735
2883
|
function displayPetInfo(petInfo: Cat | Dog) {
|
|
1736
2884
|
// typeof petInfo =>
|
|
1737
2885
|
// {
|
|
@@ -1744,7 +2892,7 @@ function displayPetInfo(petInfo: Cat | Dog) {
|
|
|
1744
2892
|
// dogType: string; // Needn't care about this field, because it's not a common pet info field.
|
|
1745
2893
|
// }
|
|
1746
2894
|
|
|
1747
|
-
// petInfo type is complex and
|
|
2895
|
+
// The `petInfo` type is complex and has some unnecessary fields.
|
|
1748
2896
|
|
|
1749
2897
|
console.log('name:', petInfo.name);
|
|
1750
2898
|
console.log('type:', petInfo.type);
|
|
@@ -1757,7 +2905,7 @@ function displayPetInfoWithSharedUnionFields(petInfo: SharedUnionFields<Cat | Do
|
|
|
1757
2905
|
// type: 'cat' | 'dog';
|
|
1758
2906
|
// }
|
|
1759
2907
|
|
|
1760
|
-
// petInfo type is simple and clear
|
|
2908
|
+
// The `petInfo` type is simple and clear.
|
|
1761
2909
|
|
|
1762
2910
|
console.log('name:', petInfo.name);
|
|
1763
2911
|
console.log('type:', petInfo.type);
|
|
@@ -1771,21 +2919,23 @@ function displayPetInfoWithSharedUnionFields(petInfo: SharedUnionFields<Cat | Do
|
|
|
1771
2919
|
@category Union
|
|
1772
2920
|
*/
|
|
1773
2921
|
type SharedUnionFields<Union> =
|
|
1774
|
-
Extract<Union, NonRecursiveType |
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
2922
|
+
Extract<Union, NonRecursiveType | UnknownCollection> extends infer SkippedMembers
|
|
2923
|
+
? Exclude<Union, SkippedMembers> extends infer RelevantMembers
|
|
2924
|
+
? // eslint-disable-line @stylistic/operator-linebreak
|
|
2925
|
+
| SkippedMembers
|
|
2926
|
+
| (IsNever<RelevantMembers> extends true
|
|
2927
|
+
? never
|
|
2928
|
+
// Keep shared index domains and declared fields separately so index signatures cannot hide known properties.
|
|
2929
|
+
: SimplifyObject<Pick<RelevantMembers, keyof RelevantMembers> & Pick<RelevantMembers, keyof OmitIndexSignature<RelevantMembers> & keyof RelevantMembers>>)
|
|
2930
|
+
: never
|
|
2931
|
+
: never;
|
|
1783
2932
|
|
|
1784
2933
|
/**
|
|
1785
2934
|
Create a type with all fields from a union of object types.
|
|
1786
2935
|
|
|
1787
2936
|
Use-cases:
|
|
1788
2937
|
- You want a safe object type where each key exists in the union object.
|
|
2938
|
+
- You want to merge the values of an object into one object type.
|
|
1789
2939
|
|
|
1790
2940
|
@example
|
|
1791
2941
|
```
|
|
@@ -1840,34 +2990,85 @@ function displayPetInfoWithAllUnionFields(petInfo: AllUnionFields<Cat | Dog>) {
|
|
|
1840
2990
|
}
|
|
1841
2991
|
```
|
|
1842
2992
|
|
|
2993
|
+
Combine it with {@link ValueOf} to merge the values of an object. A key that is in every value is required, and a key that is in only some of the values is optional.
|
|
2994
|
+
|
|
2995
|
+
@example
|
|
2996
|
+
```
|
|
2997
|
+
import type {AllUnionFields, ValueOf} from 'type-fest';
|
|
2998
|
+
|
|
2999
|
+
const steps = {
|
|
3000
|
+
install: {title: 'Install the app'},
|
|
3001
|
+
login: {title: 'Log in', description: 'Use your GitHub account'},
|
|
3002
|
+
finish: {title: 'Done'},
|
|
3003
|
+
};
|
|
3004
|
+
|
|
3005
|
+
type Step = AllUnionFields<ValueOf<typeof steps>>;
|
|
3006
|
+
//=> {title: string; description?: string}
|
|
3007
|
+
```
|
|
3008
|
+
|
|
3009
|
+
Note: If one union member has a string enum key and another member has a plain string key with the same value, that field is left out of the result. Use the same spelling in every member.
|
|
3010
|
+
|
|
1843
3011
|
@see {@link SharedUnionFields}
|
|
1844
3012
|
|
|
1845
3013
|
@category Object
|
|
1846
3014
|
@category Union
|
|
1847
3015
|
*/
|
|
1848
3016
|
type AllUnionFields<Union> =
|
|
1849
|
-
Extract<Union, NonRecursiveType |
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
3017
|
+
Extract<Union, NonRecursiveType | UnknownCollection> extends infer SkippedMembers
|
|
3018
|
+
? NormalizeNumericKeys<Exclude<Union, SkippedMembers>> extends infer RelevantMembers
|
|
3019
|
+
? // eslint-disable-line @stylistic/operator-linebreak
|
|
3020
|
+
| SkippedMembers
|
|
3021
|
+
| SimplifyObject<
|
|
3022
|
+
// Include fields that are common in all union members
|
|
3023
|
+
SharedUnionFields<RelevantMembers>
|
|
3024
|
+
// Include readonly fields present in any union member
|
|
3025
|
+
& {
|
|
3026
|
+
readonly [P in ReadonlyKeysOf<Extract<RelevantMembers, object>>]?: FieldValue<RelevantMembers, P>
|
|
3027
|
+
}
|
|
3028
|
+
// Include remaining fields that are neither common nor readonly
|
|
3029
|
+
& {
|
|
3030
|
+
[P in Exclude<KeysOfUnion<RelevantMembers>, ReadonlyKeysOf<Extract<RelevantMembers, object>> | keyof RelevantMembers>]?: FieldValue<RelevantMembers, P>
|
|
3031
|
+
}
|
|
3032
|
+
>
|
|
3033
|
+
: never
|
|
3034
|
+
: never;
|
|
3035
|
+
|
|
3036
|
+
/**
|
|
3037
|
+
Get the values of the members that have the given key. Unlike `ValueOf`, a broad key, like `string`, reads only the members whose index signatures cover it and not the named properties it covers, so each index signature of the result keeps the values of its own index domain.
|
|
3038
|
+
*/
|
|
3039
|
+
type FieldValue<Union, Key extends PropertyKey> =
|
|
3040
|
+
Union extends unknown
|
|
3041
|
+
? Key extends keyof Union ? Union[Key] : never
|
|
3042
|
+
: never;
|
|
3043
|
+
|
|
3044
|
+
/**
|
|
3045
|
+
Use an existing numeric key for its exact canonical string spelling, so merging cannot drop duplicate aliases. Leave other unions as is to preserve index signatures.
|
|
3046
|
+
*/
|
|
3047
|
+
type NormalizeNumericKeys<Union, AllKeys extends PropertyKey = KeysOfUnion<Union>> =
|
|
3048
|
+
IsNumericLiteral<ExistingNumericKey<AllKeys, AllKeys>> extends true
|
|
3049
|
+
? Union extends unknown
|
|
3050
|
+
? {[Key in keyof Union as
|
|
3051
|
+
ExistingNumericKey<Key, AllKeys> extends infer NumericKey extends number
|
|
3052
|
+
? NumericKey | Exclude<Key, `${NumericKey}`>
|
|
3053
|
+
: never
|
|
3054
|
+
]: Union[Key]}
|
|
3055
|
+
: never
|
|
3056
|
+
: Union;
|
|
3057
|
+
|
|
3058
|
+
/**
|
|
3059
|
+
Get the key in `AllKeys` that the numeric string spelling `Key` names. A `number` index signature covers every numeric key.
|
|
3060
|
+
*/
|
|
3061
|
+
type ExistingNumericKey<Key, AllKeys> =
|
|
3062
|
+
StringToNumber<Extract<Key, `${number}`>> extends infer NumberKey
|
|
3063
|
+
// Compare the string spellings, because `number` is assignable to a numeric enum.
|
|
3064
|
+
? `${number}` extends `${AllKeys & number}` ? NumberKey : Extract<AllKeys, NumberKey>
|
|
3065
|
+
: never;
|
|
1867
3066
|
|
|
1868
3067
|
/**
|
|
1869
3068
|
Returns a boolean for whether the given string literal is lowercase.
|
|
1870
3069
|
|
|
3070
|
+
Checks union members separately; mixed results return `boolean`. Returns `boolean` for `any` and `false` for `never`. Only string inputs are accepted.
|
|
3071
|
+
|
|
1871
3072
|
@example
|
|
1872
3073
|
```
|
|
1873
3074
|
import type {IsLowercase} from 'type-fest';
|
|
@@ -1882,13 +3083,21 @@ type C = IsLowercase<string>;
|
|
|
1882
3083
|
//=> boolean
|
|
1883
3084
|
```
|
|
1884
3085
|
*/
|
|
1885
|
-
type IsLowercase<S extends string> =
|
|
3086
|
+
type IsLowercase<S extends string> =
|
|
3087
|
+
// Check a whole literal directly to avoid a character walk and its recursion limit.
|
|
3088
|
+
IsStringLiteral<S> extends true
|
|
3089
|
+
// The template form reads a string enum member by its value, since the member itself is not assignable to `Lowercase<string>`.
|
|
3090
|
+
? S extends unknown
|
|
3091
|
+
? `${UnwrapBrandedPrimitive<S>}` extends Lowercase<string> ? true : false
|
|
3092
|
+
: never
|
|
3093
|
+
: AllExtend<_IsLowercase<S>, true>;
|
|
1886
3094
|
|
|
1887
3095
|
/**
|
|
1888
3096
|
Loops through each part in the string and returns a boolean array indicating whether each part is lowercase.
|
|
1889
3097
|
*/
|
|
1890
3098
|
type _IsLowercase<S extends string, Accumulator extends boolean[] = []> = S extends `${infer First}${infer Rest}`
|
|
1891
|
-
|
|
3099
|
+
// A known mismatch decides the result even when the rest of the input is long or unknown.
|
|
3100
|
+
? IsLowercaseHelper<First> extends false ? [false] : _IsLowercase<Rest, [...Accumulator, IsLowercaseHelper<First>]>
|
|
1892
3101
|
: [...Accumulator, IsLowercaseHelper<S>];
|
|
1893
3102
|
|
|
1894
3103
|
/**
|
|
@@ -1898,11 +3107,16 @@ type IsLowercaseHelper<S extends string> = S extends Lowercase<string>
|
|
|
1898
3107
|
? true
|
|
1899
3108
|
: S extends Uppercase<string> | Capitalize<string> | `${string}${Uppercase<string>}${string}`
|
|
1900
3109
|
? false
|
|
1901
|
-
|
|
3110
|
+
// A titlecase character is changed by both lowercasing and uppercasing, so it is neither, but none of the patterns above name it either.
|
|
3111
|
+
: S extends TitlecaseCharacter
|
|
3112
|
+
? false
|
|
3113
|
+
: boolean;
|
|
1902
3114
|
|
|
1903
3115
|
/**
|
|
1904
3116
|
Returns a boolean for whether the given string literal is uppercase.
|
|
1905
3117
|
|
|
3118
|
+
Checks union members separately; mixed results return `boolean`. Returns `boolean` for `any` and `false` for `never`. Only string inputs are accepted.
|
|
3119
|
+
|
|
1906
3120
|
@example
|
|
1907
3121
|
```
|
|
1908
3122
|
import type {IsUppercase} from 'type-fest';
|
|
@@ -1917,13 +3131,21 @@ type C = IsUppercase<string>;
|
|
|
1917
3131
|
//=> boolean
|
|
1918
3132
|
```
|
|
1919
3133
|
*/
|
|
1920
|
-
type IsUppercase<S extends string> =
|
|
3134
|
+
type IsUppercase<S extends string> =
|
|
3135
|
+
// Check a whole literal directly to avoid a character walk and its recursion limit.
|
|
3136
|
+
IsStringLiteral<S> extends true
|
|
3137
|
+
// The template form reads a string enum member by its value, since the member itself is not assignable to `Uppercase<string>`.
|
|
3138
|
+
? S extends unknown
|
|
3139
|
+
? `${UnwrapBrandedPrimitive<S>}` extends Uppercase<string> ? true : false
|
|
3140
|
+
: never
|
|
3141
|
+
: AllExtend<_IsUppercase<S>, true>;
|
|
1921
3142
|
|
|
1922
3143
|
/**
|
|
1923
3144
|
Loops through each part in the string and returns a boolean array indicating whether each part is uppercase.
|
|
1924
3145
|
*/
|
|
1925
3146
|
type _IsUppercase<S extends string, Accumulator extends boolean[] = []> = S extends `${infer First}${infer Rest}`
|
|
1926
|
-
|
|
3147
|
+
// A known mismatch decides the result even when the rest of the input is long or unknown.
|
|
3148
|
+
? IsUppercaseHelper<First> extends false ? [false] : _IsUppercase<Rest, [...Accumulator, IsUppercaseHelper<First>]>
|
|
1927
3149
|
: [...Accumulator, IsUppercaseHelper<S>];
|
|
1928
3150
|
|
|
1929
3151
|
/**
|
|
@@ -1933,7 +3155,10 @@ type IsUppercaseHelper<S extends string> = S extends Uppercase<string>
|
|
|
1933
3155
|
? true
|
|
1934
3156
|
: S extends Lowercase<string> | Uncapitalize<string> | `${string}${Lowercase<string>}${string}`
|
|
1935
3157
|
? false
|
|
1936
|
-
|
|
3158
|
+
// A titlecase character is changed by both lowercasing and uppercasing, so it is neither, but none of the patterns above name it either.
|
|
3159
|
+
: S extends TitlecaseCharacter
|
|
3160
|
+
? false
|
|
3161
|
+
: boolean;
|
|
1937
3162
|
|
|
1938
3163
|
type SkipEmptyWord<Word extends string> = Word extends '' ? [] : [Word];
|
|
1939
3164
|
|
|
@@ -1945,7 +3170,7 @@ type RemoveLastCharacter<
|
|
|
1945
3170
|
: never;
|
|
1946
3171
|
|
|
1947
3172
|
/**
|
|
1948
|
-
Words
|
|
3173
|
+
Options for the `Words` type.
|
|
1949
3174
|
|
|
1950
3175
|
@see {@link Words}
|
|
1951
3176
|
*/
|
|
@@ -1953,7 +3178,7 @@ type WordsOptions = {
|
|
|
1953
3178
|
/**
|
|
1954
3179
|
Split on numeric sequence.
|
|
1955
3180
|
|
|
1956
|
-
@default true
|
|
3181
|
+
@default `true` for `Words`, and `false` for the case conversion types, such as `CamelCase` and `KebabCase`
|
|
1957
3182
|
|
|
1958
3183
|
@example
|
|
1959
3184
|
```
|
|
@@ -1967,120 +3192,159 @@ type WordsOptions = {
|
|
|
1967
3192
|
```
|
|
1968
3193
|
*/
|
|
1969
3194
|
splitOnNumbers?: boolean;
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
type _DefaultWordsOptions = {
|
|
1973
|
-
splitOnNumbers: true;
|
|
1974
|
-
};
|
|
1975
|
-
|
|
1976
|
-
/**
|
|
1977
|
-
Split a string (almost) like Lodash's `_.words()` function.
|
|
1978
|
-
|
|
1979
|
-
- Split on each word that begins with a capital letter.
|
|
1980
|
-
- Split on each {@link WordSeparators}.
|
|
1981
|
-
- Split on numeric sequence.
|
|
1982
|
-
|
|
1983
|
-
@example
|
|
1984
|
-
```
|
|
1985
|
-
import type {Words} from 'type-fest';
|
|
1986
|
-
|
|
1987
|
-
type Words0 = Words<'helloWorld'>;
|
|
1988
|
-
//=> ['hello', 'World']
|
|
3195
|
+
/**
|
|
3196
|
+
Split on {@link AsciiPunctuationCharacter | ASCII punctuation characters} (for example, `#`, `&`, `*`, `:`, `?`, `@`, `~`). Hyphens and underscores always separate words, regardless of this option.
|
|
1989
3197
|
|
|
1990
|
-
|
|
1991
|
-
//=> ['hello', 'WORLD']
|
|
3198
|
+
@default true
|
|
1992
3199
|
|
|
1993
|
-
|
|
1994
|
-
|
|
3200
|
+
@example
|
|
3201
|
+
```
|
|
3202
|
+
import type {Words} from 'type-fest';
|
|
1995
3203
|
|
|
1996
|
-
type
|
|
1997
|
-
//=> ['hello', '
|
|
3204
|
+
type Example1 = Words<'hello:world', {splitOnPunctuation: true}>;
|
|
3205
|
+
//=> ['hello', 'world']
|
|
1998
3206
|
|
|
1999
|
-
type
|
|
2000
|
-
//=> ['
|
|
3207
|
+
type Example2 = Words<'hello:world', {splitOnPunctuation: false}>;
|
|
3208
|
+
//=> ['hello:world']
|
|
3209
|
+
```
|
|
3210
|
+
*/
|
|
3211
|
+
splitOnPunctuation?: boolean;
|
|
3212
|
+
};
|
|
2001
3213
|
|
|
2002
|
-
type
|
|
2003
|
-
|
|
2004
|
-
|
|
3214
|
+
type _DefaultWordsOptions = {
|
|
3215
|
+
splitOnNumbers: true;
|
|
3216
|
+
splitOnPunctuation: true;
|
|
3217
|
+
}; // Should never happen, since `Sentence` is a string
|
|
2005
3218
|
|
|
2006
|
-
|
|
2007
|
-
|
|
3219
|
+
/**
|
|
3220
|
+
Splits a known unbranded string literal using resolved options. Casing types reuse this entry point after checking and normalizing their own inputs.
|
|
2008
3221
|
*/
|
|
2009
|
-
type
|
|
2010
|
-
WordsImplementation<Sentence, ApplyDefaultOptions<WordsOptions, _DefaultWordsOptions, Options>>;
|
|
2011
|
-
|
|
2012
|
-
type WordsImplementation<
|
|
3222
|
+
type _Words<
|
|
2013
3223
|
Sentence extends string,
|
|
2014
3224
|
Options extends Required<WordsOptions>,
|
|
2015
3225
|
LastCharacter extends string = '',
|
|
2016
3226
|
CurrentWord extends string = '',
|
|
3227
|
+
// The words found so far are kept in `Result`, so the recursion is in tail position and a long sentence does not hit the recursion limit.
|
|
3228
|
+
Result extends string[] = [],
|
|
2017
3229
|
> = Sentence extends `${infer FirstCharacter}${infer RemainingCharacters}`
|
|
2018
|
-
? FirstCharacter extends WordSeparators
|
|
3230
|
+
? FirstCharacter extends WordSeparators | (Options['splitOnPunctuation'] extends false ? never : AsciiPunctuationCharacter)
|
|
2019
3231
|
// Skip word separator
|
|
2020
|
-
? [...SkipEmptyWord<CurrentWord
|
|
3232
|
+
? _Words<RemainingCharacters, Options, '', '', [...Result, ...SkipEmptyWord<CurrentWord>]>
|
|
2021
3233
|
: LastCharacter extends ''
|
|
2022
|
-
//
|
|
2023
|
-
?
|
|
2024
|
-
// Case change
|
|
2025
|
-
: [false, true]
|
|
3234
|
+
// First character of word
|
|
3235
|
+
? _Words<RemainingCharacters, Options, FirstCharacter, FirstCharacter, Result>
|
|
3236
|
+
// Case change between numeric and non-numeric characters.
|
|
3237
|
+
: [IsDigit<LastCharacter>, IsDigit<FirstCharacter>] extends [false, true] | [true, false]
|
|
2026
3238
|
? Options['splitOnNumbers'] extends true
|
|
2027
3239
|
// Split on number: push word
|
|
2028
|
-
?
|
|
3240
|
+
? _Words<RemainingCharacters, Options, FirstCharacter, FirstCharacter, [...Result, ...SkipEmptyWord<CurrentWord>]>
|
|
2029
3241
|
// No split on number: concat word
|
|
2030
|
-
:
|
|
2031
|
-
//
|
|
2032
|
-
: [true,
|
|
2033
|
-
? Options
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
//
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
? [
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
:
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
3242
|
+
: _Words<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`, Result>
|
|
3243
|
+
// No case change: concat word
|
|
3244
|
+
: [true, true] extends [IsDigit<LastCharacter>, IsDigit<FirstCharacter>]
|
|
3245
|
+
? _Words<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`, Result>
|
|
3246
|
+
// Case change: lower to upper, push word
|
|
3247
|
+
: [true, true] extends [IsLowercase<LastCharacter>, IsUppercase<FirstCharacter>]
|
|
3248
|
+
// Only a capital letter starts a new word. A character with no case at all, such as a Han character or an emoji, satisfies both case predicates but is its own lowercase form, so it is not one.
|
|
3249
|
+
? IsCapitalLetter<FirstCharacter> extends true
|
|
3250
|
+
? _Words<RemainingCharacters, Options, FirstCharacter, FirstCharacter, [...Result, ...SkipEmptyWord<CurrentWord>]>
|
|
3251
|
+
: _Words<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`, Result>
|
|
3252
|
+
// Case change: upper to lower, brings back the last character, push word
|
|
3253
|
+
: [true, true] extends [IsUppercase<LastCharacter>, IsLowercase<FirstCharacter>]
|
|
3254
|
+
// Only a capital followed by a lowercase letter starts a new word. Punctuation or a character with no case after an acronym, as in `userID?`, satisfies both case predicates, so it would otherwise split off the last capital.
|
|
3255
|
+
? [IsCapitalLetter<LastCharacter>, IsLowercaseLetter<FirstCharacter>] extends [true, true]
|
|
3256
|
+
? _Words<
|
|
3257
|
+
RemainingCharacters, Options, FirstCharacter, `${LastCharacter}${FirstCharacter}`,
|
|
3258
|
+
[...Result, ...RemoveLastCharacter<CurrentWord, LastCharacter>]
|
|
3259
|
+
>
|
|
3260
|
+
: _Words<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`, Result>
|
|
3261
|
+
// No case change: concat word
|
|
3262
|
+
: _Words<RemainingCharacters, Options, FirstCharacter, `${CurrentWord}${FirstCharacter}`, Result>
|
|
3263
|
+
: [...Result, ...SkipEmptyWord<CurrentWord>];
|
|
3264
|
+
|
|
3265
|
+
/**
|
|
3266
|
+
Whether the given character is an ASCII decimal digit.
|
|
3267
|
+
*/
|
|
3268
|
+
type IsDigit<Character extends string> = Character extends DigitCharacter ? true : false;
|
|
3269
|
+
|
|
3270
|
+
/**
|
|
3271
|
+
Whether the given character is a capital letter, which is what decides whether it begins a new word.
|
|
3272
|
+
|
|
3273
|
+
A character with no case at all, such as a Han character or an emoji, is its own lowercase form and so is not a capital. Every other cased character is, in any script, so this is deliberately not restricted to ASCII: `É` and `Ä` are capitals just as `A` is.
|
|
3274
|
+
*/
|
|
3275
|
+
type IsCapitalLetter<Character extends string> = Lowercase<Character> extends Character ? false : true;
|
|
3276
|
+
|
|
3277
|
+
/**
|
|
3278
|
+
Whether the given character is a lowercase letter, which is what decides whether a preceding capital begins a new word.
|
|
3279
|
+
|
|
3280
|
+
Like {@link IsCapitalLetter}, a character with no case at all, such as punctuation, a Han character, or an emoji, is its own uppercase form and so is not a lowercase letter.
|
|
3281
|
+
*/
|
|
3282
|
+
type IsLowercaseLetter<Character extends string> = Uppercase<Character> extends Character ? false : true;
|
|
3283
|
+
|
|
3284
|
+
/**
|
|
3285
|
+
Options for the `CamelCase` type.
|
|
2053
3286
|
|
|
2054
3287
|
@see {@link CamelCase}
|
|
2055
3288
|
*/
|
|
2056
3289
|
type CamelCaseOptions = WordsOptions & {
|
|
2057
3290
|
/**
|
|
2058
|
-
Whether to
|
|
3291
|
+
Whether to preserve consecutive uppercase letters.
|
|
3292
|
+
|
|
3293
|
+
Note: A string that is entirely uppercase, such as `'FOO_BAR'`, is lowercased before it is split into words, so the option has no effect on it and the result is `'fooBar'` either way. This keeps `CamelCase<'FOO_BAR'>` the same regardless of the option.
|
|
2059
3294
|
|
|
2060
3295
|
@default false
|
|
2061
3296
|
*/
|
|
2062
3297
|
preserveConsecutiveUppercase?: boolean;
|
|
3298
|
+
|
|
3299
|
+
/**
|
|
3300
|
+
Whether to preserve leading underscores, like in `_id` and `__typename`.
|
|
3301
|
+
|
|
3302
|
+
This matches the behavior of the [`camelcase`](https://github.com/sindresorhus/camelcase) package v9+. Unlike that package, a leading `$` is removed with the default `splitOnPunctuation` option, because it is ASCII punctuation, which separates words.
|
|
3303
|
+
|
|
3304
|
+
@default true
|
|
3305
|
+
*/
|
|
3306
|
+
preserveLeadingUnderscores?: boolean;
|
|
2063
3307
|
};
|
|
2064
3308
|
|
|
2065
|
-
type _DefaultCamelCaseOptions = {
|
|
2066
|
-
splitOnNumbers:
|
|
3309
|
+
type _DefaultCamelCaseOptions = Merge<_DefaultWordsOptions, {
|
|
3310
|
+
splitOnNumbers: false;
|
|
2067
3311
|
preserveConsecutiveUppercase: false;
|
|
2068
|
-
|
|
3312
|
+
preserveLeadingUnderscores: true;
|
|
3313
|
+
}>;
|
|
3314
|
+
|
|
3315
|
+
/**
|
|
3316
|
+
Extract leading underscores from a string.
|
|
3317
|
+
|
|
3318
|
+
@example
|
|
3319
|
+
```
|
|
3320
|
+
type A = LeadingUnderscores<'__foo_bar'>;
|
|
3321
|
+
//=> '__'
|
|
3322
|
+
|
|
3323
|
+
type B = LeadingUnderscores<'foo_bar'>;
|
|
3324
|
+
//=> ''
|
|
3325
|
+
```
|
|
3326
|
+
*/
|
|
3327
|
+
type LeadingUnderscores<Type extends string, Underscores extends string = ''> =
|
|
3328
|
+
Type extends `_${infer Rest}`
|
|
3329
|
+
? LeadingUnderscores<Rest, `_${Underscores}`>
|
|
3330
|
+
: Underscores;
|
|
2069
3331
|
|
|
2070
3332
|
/**
|
|
2071
3333
|
Convert an array of words to camel-case.
|
|
3334
|
+
|
|
3335
|
+
The first word is uncapitalized and every other word is capitalized. The first word is never capitalized and then uncapitalized again, because `Capitalize<'ß'>` is `'SS'` and `Uncapitalize<'SS'>` is `'sS'`.
|
|
2072
3336
|
*/
|
|
2073
3337
|
type CamelCaseFromArray<
|
|
2074
|
-
|
|
3338
|
+
WordList extends string[],
|
|
2075
3339
|
Options extends Required<CamelCaseOptions>,
|
|
2076
3340
|
OutputString extends string = '',
|
|
2077
|
-
> =
|
|
3341
|
+
> = WordList extends [
|
|
2078
3342
|
infer FirstWord extends string,
|
|
2079
3343
|
...infer RemainingWords extends string[],
|
|
2080
3344
|
]
|
|
2081
|
-
? Options['preserveConsecutiveUppercase'] extends true
|
|
2082
|
-
?
|
|
2083
|
-
:
|
|
3345
|
+
? (Options['preserveConsecutiveUppercase'] extends true ? FirstWord : Lowercase<FirstWord>) extends infer Word extends string
|
|
3346
|
+
? CamelCaseFromArray<RemainingWords, Options, OutputString extends '' ? Uncapitalize<Word> : `${OutputString}${Capitalize<Word>}`>
|
|
3347
|
+
: never
|
|
2084
3348
|
: OutputString;
|
|
2085
3349
|
|
|
2086
3350
|
/**
|
|
@@ -2088,7 +3352,11 @@ Convert a string literal to camel-case.
|
|
|
2088
3352
|
|
|
2089
3353
|
This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
|
|
2090
3354
|
|
|
2091
|
-
By default, consecutive uppercase
|
|
3355
|
+
By default, consecutive uppercase letters are not preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour.
|
|
3356
|
+
|
|
3357
|
+
Leading underscores are kept, matching the runtime behavior of [`camelcase`](https://github.com/sindresorhus/camelcase) v9+. Set the `preserveLeadingUnderscores` option to `false` to remove them.
|
|
3358
|
+
|
|
3359
|
+
In a generic function, use concrete option values before relying on an exact result spelling. While any option is generic, TypeScript can read the result as if the default options were used.
|
|
2092
3360
|
|
|
2093
3361
|
@example
|
|
2094
3362
|
```
|
|
@@ -2098,6 +3366,12 @@ import type {CamelCase} from 'type-fest';
|
|
|
2098
3366
|
|
|
2099
3367
|
const someVariable: CamelCase<'foo-bar'> = 'fooBar';
|
|
2100
3368
|
const preserveConsecutiveUppercase: CamelCase<'foo-BAR-baz', {preserveConsecutiveUppercase: true}> = 'fooBARBaz';
|
|
3369
|
+
const noSplitOnNumbers: CamelCase<'p2p_network'> = 'p2pNetwork';
|
|
3370
|
+
const splitOnNumbers: CamelCase<'p2p_network', {splitOnNumbers: true}> = 'p2PNetwork';
|
|
3371
|
+
const splitOnPunctuation: CamelCase<'foo-bar:BAZ'> = 'fooBarBaz';
|
|
3372
|
+
const noSplitOnPunctuation: CamelCase<'foo-bar:baz', {splitOnPunctuation: false}> = 'fooBar:baz';
|
|
3373
|
+
const preserveLeadingUnderscores: CamelCase<'_foo_bar'> = '_fooBar';
|
|
3374
|
+
const noPreserveLeadingUnderscores: CamelCase<'_foo_bar', {preserveLeadingUnderscores: false}> = 'fooBar';
|
|
2101
3375
|
|
|
2102
3376
|
// Advanced
|
|
2103
3377
|
|
|
@@ -2128,14 +3402,23 @@ const dbResult: CamelCasedProperties<RawOptions> = {
|
|
|
2128
3402
|
@category Template literal
|
|
2129
3403
|
*/
|
|
2130
3404
|
type CamelCase<Type, Options extends CamelCaseOptions = {}> = Type extends string
|
|
2131
|
-
?
|
|
3405
|
+
? IsStringLiteral<Type> extends false
|
|
2132
3406
|
? Type
|
|
2133
|
-
:
|
|
2134
|
-
|
|
2135
|
-
ApplyDefaultOptions<CamelCaseOptions, _DefaultCamelCaseOptions, Options>
|
|
2136
|
-
>>
|
|
3407
|
+
// The brand is removed first, because the entirely-uppercase pre-lowering and the leading underscores must read the string itself: an intersection with a brand does not reduce under `Uppercase` and does not match `_`. The word splitter can then reuse the normalized input and resolved options.
|
|
3408
|
+
: CamelCaseUnbranded<UnwrapBrandedPrimitive<Type>, Options>
|
|
2137
3409
|
: Type;
|
|
2138
3410
|
|
|
3411
|
+
type CamelCaseUnbranded<Type extends string, Options extends CamelCaseOptions> =
|
|
3412
|
+
ApplyDefaultOptions<CamelCaseOptions, _DefaultCamelCaseOptions, Options> extends infer OptionsWithDefaults extends Required<CamelCaseOptions>
|
|
3413
|
+
? `${OptionsWithDefaults['preserveLeadingUnderscores'] extends false
|
|
3414
|
+
? ''
|
|
3415
|
+
: LeadingUnderscores<Type>
|
|
3416
|
+
}${CamelCaseFromArray<
|
|
3417
|
+
_Words<Type extends Uppercase<Type> ? Lowercase<Type> : Type, OptionsWithDefaults>,
|
|
3418
|
+
OptionsWithDefaults
|
|
3419
|
+
>}`
|
|
3420
|
+
: never;
|
|
3421
|
+
|
|
2139
3422
|
/**
|
|
2140
3423
|
* This is a fork of the Help class from the 'commander' npm package. The Help class method names as well as the
|
|
2141
3424
|
* expected interface of the Command instance to parse, are both similar, but different and not compatible without
|