@storybook/react 10.5.0-alpha.2 → 10.5.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/preview.d.ts CHANGED
@@ -3,99 +3,390 @@ import { PreviewAddon, InferTypes, AddonTypes, Preview, Meta, Story } from 'stor
3
3
  import { WebRenderer, Canvas, ProjectAnnotations, Args, DecoratorFunction, ArgsStoryFn, ComponentAnnotations, StoryAnnotations, Renderer } from 'storybook/internal/types';
4
4
  import { RootOptions } from 'react-dom/client';
5
5
 
6
- declare global {
7
- interface SymbolConstructor {
8
- readonly observable: symbol;
9
- }
10
- }
11
-
12
6
  /**
13
- Returns a boolean for whether the two given types are equal.
7
+ Convert a union type to an intersection type.
14
8
 
15
- @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
16
- @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
9
+ Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
10
+
11
+ @example
12
+ ```
13
+ import type {UnionToIntersection} from 'type-fest';
14
+
15
+ type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
16
+
17
+ type Intersection = UnionToIntersection<Union>;
18
+ //=> {the(): void} & {great(arg: string): void} & {escape: boolean}
19
+ ```
20
+
21
+ @category Type
17
22
  */
18
- type IsEqual<T, U> =
19
- (<G>() => G extends T ? 1 : 2) extends
20
- (<G>() => G extends U ? 1 : 2)
21
- ? true
22
- : false;
23
+ type UnionToIntersection<Union> = (
24
+ // `extends unknown` is always going to be the case and is used to convert the
25
+ // `Union` into a [distributive conditional
26
+ // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
27
+ Union extends unknown
28
+ // The union type is used as the only argument to a function since the union
29
+ // of function arguments is an intersection.
30
+ ? (distributedUnion: Union) => void
31
+ // This won't happen.
32
+ : never
33
+ // Infer the `Intersection` type since TypeScript represents the positional
34
+ // arguments of unions of functions as an intersection of the union.
35
+ ) extends ((mergedIntersection: infer Intersection) => void)
36
+ // The `& Union` is to ensure result of `UnionToIntersection<A | B>` is always assignable to `A | B`
37
+ ? Intersection & Union
38
+ : never;
23
39
 
24
40
  /**
25
- Filter out keys from an object.
41
+ Create a union of all keys from a given type, even those exclusive to specific union members.
26
42
 
27
- Returns `never` if `Exclude` is strictly equal to `Key`.
28
- Returns `never` if `Key` extends `Exclude`.
29
- Returns `Key` otherwise.
43
+ Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
44
+
45
+ @link https://stackoverflow.com/a/49402091
30
46
 
31
47
  @example
32
48
  ```
33
- type Filtered = Filter<'foo', 'foo'>;
34
- //=> never
49
+ import type {KeysOfUnion} from 'type-fest';
50
+
51
+ type A = {
52
+ common: string;
53
+ a: number;
54
+ };
55
+
56
+ type B = {
57
+ common: string;
58
+ b: string;
59
+ };
60
+
61
+ type C = {
62
+ common: string;
63
+ c: boolean;
64
+ };
65
+
66
+ type Union = A | B | C;
67
+
68
+ type CommonKeys = keyof Union;
69
+ //=> 'common'
70
+
71
+ type AllKeys = KeysOfUnion<Union>;
72
+ //=> 'common' | 'a' | 'b' | 'c'
35
73
  ```
36
74
 
75
+ @category Object
76
+ */
77
+ type KeysOfUnion<ObjectType> =
78
+ // Hack to fix https://github.com/sindresorhus/type-fest/issues/1008
79
+ keyof UnionToIntersection<ObjectType extends unknown ? Record<keyof ObjectType, never> : never>;
80
+
81
+ /**
82
+ Returns a boolean for whether the given type is `any`.
83
+
84
+ @link https://stackoverflow.com/a/49928360/1490091
85
+
86
+ Useful in type utilities, such as disallowing `any`s to be passed to a function.
87
+
37
88
  @example
38
89
  ```
39
- type Filtered = Filter<'bar', string>;
40
- //=> never
90
+ import type {IsAny} from 'type-fest';
91
+
92
+ const typedObject = {a: 1, b: 2} as const;
93
+ const anyObject: any = {a: 1, b: 2};
94
+
95
+ function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(object: O, key: K) {
96
+ return object[key];
97
+ }
98
+
99
+ const typedA = get(typedObject, 'a');
100
+ //=> 1
101
+
102
+ const anyA = get(anyObject, 'a');
103
+ //=> any
41
104
  ```
42
105
 
106
+ @category Type Guard
107
+ @category Utilities
108
+ */
109
+ type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
110
+
111
+ /**
112
+ Returns a boolean for whether the given key is an optional key of type.
113
+
114
+ This is useful when writing utility types or schema validators that need to differentiate `optional` keys.
115
+
43
116
  @example
44
117
  ```
45
- type Filtered = Filter<'bar', 'foo'>;
46
- //=> 'bar'
118
+ import type {IsOptionalKeyOf} from 'type-fest';
119
+
120
+ type User = {
121
+ name: string;
122
+ surname: string;
123
+
124
+ luckyNumber?: number;
125
+ };
126
+
127
+ type Admin = {
128
+ name: string;
129
+ surname?: string;
130
+ };
131
+
132
+ type T1 = IsOptionalKeyOf<User, 'luckyNumber'>;
133
+ //=> true
134
+
135
+ type T2 = IsOptionalKeyOf<User, 'name'>;
136
+ //=> false
137
+
138
+ type T3 = IsOptionalKeyOf<User, 'name' | 'luckyNumber'>;
139
+ //=> boolean
140
+
141
+ type T4 = IsOptionalKeyOf<User | Admin, 'name'>;
142
+ //=> false
143
+
144
+ type T5 = IsOptionalKeyOf<User | Admin, 'surname'>;
145
+ //=> boolean
47
146
  ```
48
147
 
49
- @see {Except}
148
+ @category Type Guard
149
+ @category Utilities
50
150
  */
51
- type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType);
151
+ type IsOptionalKeyOf<Type extends object, Key extends keyof Type> =
152
+ IsAny<Type | Key> extends true ? never
153
+ : Key extends keyof Type
154
+ ? Type extends Record<Key, Type[Key]>
155
+ ? false
156
+ : true
157
+ : false;
52
158
 
53
159
  /**
54
- Create a type from an object type without certain keys.
160
+ Extract all optional keys from the given type.
55
161
 
56
- This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
57
-
58
- This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
162
+ This is useful when you want to create a new type that contains different type values for the optional keys only.
59
163
 
60
164
  @example
61
165
  ```
62
- import type {Except} from 'type-fest';
166
+ import type {OptionalKeysOf, Except} from 'type-fest';
63
167
 
64
- type Foo = {
65
- a: number;
66
- b: string;
67
- c: boolean;
168
+ type User = {
169
+ name: string;
170
+ surname: string;
171
+
172
+ luckyNumber?: number;
173
+ };
174
+
175
+ const REMOVE_FIELD = Symbol('remove field symbol');
176
+ type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
177
+ [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
68
178
  };
69
179
 
70
- type FooWithoutA = Except<Foo, 'a' | 'c'>;
71
- //=> {b: string};
180
+ const update1: UpdateOperation<User> = {
181
+ name: 'Alice',
182
+ };
183
+
184
+ const update2: UpdateOperation<User> = {
185
+ name: 'Bob',
186
+ luckyNumber: REMOVE_FIELD,
187
+ };
72
188
  ```
73
189
 
74
- @category Object
190
+ @category Utilities
75
191
  */
76
- type Except<ObjectType, KeysType extends keyof ObjectType> = {
77
- [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
192
+ type OptionalKeysOf<Type extends object> =
193
+ Type extends unknown // For distributing `Type`
194
+ ? (keyof {[Key in keyof Type as
195
+ IsOptionalKeyOf<Type, Key> extends false
196
+ ? never
197
+ : Key
198
+ ]: never
199
+ }) & keyof Type // Intersect with `keyof Type` to ensure result of `OptionalKeysOf<Type>` is always assignable to `keyof Type`
200
+ : never; // Should never happen
201
+
202
+ /**
203
+ Extract all required keys from the given type.
204
+
205
+ 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...
206
+
207
+ @example
208
+ ```
209
+ import type {RequiredKeysOf} from 'type-fest';
210
+
211
+ declare function createValidation<
212
+ Entity extends object,
213
+ Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>,
214
+ >(field: Key, validator: (value: Entity[Key]) => boolean): (entity: Entity) => boolean;
215
+
216
+ type User = {
217
+ name: string;
218
+ surname: string;
219
+ luckyNumber?: number;
78
220
  };
79
221
 
222
+ const validator1 = createValidation<User>('name', value => value.length < 25);
223
+ const validator2 = createValidation<User>('surname', value => value.length < 25);
224
+
225
+ // @ts-expect-error
226
+ const validator3 = createValidation<User>('luckyNumber', value => value > 0);
227
+ // Error: Argument of type '"luckyNumber"' is not assignable to parameter of type '"name" | "surname"'.
228
+ ```
229
+
230
+ @category Utilities
231
+ */
232
+ type RequiredKeysOf<Type extends object> =
233
+ Type extends unknown // For distributing `Type`
234
+ ? Exclude<keyof Type, OptionalKeysOf<Type>>
235
+ : never; // Should never happen
236
+
80
237
  /**
81
- @see Simplify
238
+ Returns a boolean for whether the given type is `never`.
239
+
240
+ @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
241
+ @link https://stackoverflow.com/a/53984913/10292952
242
+ @link https://www.zhenghao.io/posts/ts-never
243
+
244
+ Useful in type utilities, such as checking if something does not occur.
245
+
246
+ @example
247
+ ```
248
+ import type {IsNever, And} from 'type-fest';
249
+
250
+ type A = IsNever<never>;
251
+ //=> true
252
+
253
+ type B = IsNever<any>;
254
+ //=> false
255
+
256
+ type C = IsNever<unknown>;
257
+ //=> false
258
+
259
+ type D = IsNever<never[]>;
260
+ //=> false
261
+
262
+ type E = IsNever<object>;
263
+ //=> false
264
+
265
+ type F = IsNever<string>;
266
+ //=> false
267
+ ```
268
+
269
+ @example
270
+ ```
271
+ import type {IsNever} from 'type-fest';
272
+
273
+ type IsTrue<T> = T extends true ? true : false;
274
+
275
+ // When a distributive conditional is instantiated with `never`, the entire conditional results in `never`.
276
+ type A = IsTrue<never>;
277
+ //=> never
278
+
279
+ // If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional.
280
+ type IsTrueFixed<T> =
281
+ IsNever<T> extends true ? false : T extends true ? true : false;
282
+
283
+ type B = IsTrueFixed<never>;
284
+ //=> false
285
+ ```
286
+
287
+ @category Type Guard
288
+ @category Utilities
82
289
  */
83
- interface SimplifyOptions {
84
- /**
85
- Do the simplification recursively.
290
+ type IsNever<T> = [T] extends [never] ? true : false;
86
291
 
87
- @default false
88
- */
89
- deep?: boolean;
90
- }
292
+ /**
293
+ An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
91
294
 
92
- // Flatten a type without worrying about the result.
93
- type Flatten<
94
- AnyType,
95
- Options extends SimplifyOptions = {},
96
- > = Options['deep'] extends true
97
- ? {[KeyType in keyof AnyType]: Simplify<AnyType[KeyType], Options>}
98
- : {[KeyType in keyof AnyType]: AnyType[KeyType]};
295
+ Use-cases:
296
+ - 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'>`.
297
+
298
+ Note:
299
+ - 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'`.
300
+ - Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
301
+
302
+ @example
303
+ ```
304
+ import type {If} from 'type-fest';
305
+
306
+ type A = If<true, 'yes', 'no'>;
307
+ //=> 'yes'
308
+
309
+ type B = If<false, 'yes', 'no'>;
310
+ //=> 'no'
311
+
312
+ type C = If<boolean, 'yes', 'no'>;
313
+ //=> 'yes' | 'no'
314
+
315
+ type D = If<any, 'yes', 'no'>;
316
+ //=> 'yes' | 'no'
317
+
318
+ type E = If<never, 'yes', 'no'>;
319
+ //=> 'no'
320
+ ```
321
+
322
+ @example
323
+ ```
324
+ import type {If, IsAny, IsNever} from 'type-fest';
325
+
326
+ type A = If<IsAny<unknown>, 'is any', 'not any'>;
327
+ //=> 'not any'
328
+
329
+ type B = If<IsNever<never>, 'is never', 'not never'>;
330
+ //=> 'is never'
331
+ ```
332
+
333
+ @example
334
+ ```
335
+ import type {If, IsEqual} from 'type-fest';
336
+
337
+ type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
338
+
339
+ type A = IfEqual<string, string, 'equal', 'not equal'>;
340
+ //=> 'equal'
341
+
342
+ type B = IfEqual<string, number, 'equal', 'not equal'>;
343
+ //=> 'not equal'
344
+ ```
345
+
346
+ 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:
347
+
348
+ @example
349
+ ```
350
+ import type {If, IsEqual, StringRepeat} from 'type-fest';
351
+
352
+ type HundredZeroes = StringRepeat<'0', 100>;
353
+
354
+ // The following implementation is not tail recursive
355
+ type Includes<S extends string, Char extends string> =
356
+ S extends `${infer First}${infer Rest}`
357
+ ? If<IsEqual<First, Char>,
358
+ 'found',
359
+ Includes<Rest, Char>>
360
+ : 'not found';
361
+
362
+ // Hence, instantiations with long strings will fail
363
+ // @ts-expect-error
364
+ type Fails = Includes<HundredZeroes, '1'>;
365
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
366
+ // Error: Type instantiation is excessively deep and possibly infinite.
367
+
368
+ // However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
369
+ type IncludesWithoutIf<S extends string, Char extends string> =
370
+ S extends `${infer First}${infer Rest}`
371
+ ? IsEqual<First, Char> extends true
372
+ ? 'found'
373
+ : IncludesWithoutIf<Rest, Char>
374
+ : 'not found';
375
+
376
+ // Now, instantiations with long strings will work
377
+ type Works = IncludesWithoutIf<HundredZeroes, '1'>;
378
+ //=> 'not found'
379
+ ```
380
+
381
+ @category Type Guard
382
+ @category Utilities
383
+ */
384
+ type If<Type extends boolean, IfBranch, ElseBranch> =
385
+ IsNever<Type> extends true
386
+ ? ElseBranch
387
+ : Type extends true
388
+ ? IfBranch
389
+ : ElseBranch;
99
390
 
100
391
  /**
101
392
  Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
@@ -142,27 +433,65 @@ const literal = {foo: 123, bar: 'hello', baz: 456};
142
433
  const someType: SomeType = literal;
143
434
  const someInterface: SomeInterface = literal;
144
435
 
145
- function fn(object: Record<string, unknown>): void {}
436
+ declare function fn(object: Record<string, unknown>): void;
146
437
 
147
438
  fn(literal); // Good: literal object type is sealed
148
439
  fn(someType); // Good: type is sealed
440
+ // @ts-expect-error
149
441
  fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
150
442
  fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
151
443
  ```
152
444
 
153
445
  @link https://github.com/microsoft/TypeScript/issues/15300
154
-
446
+ @see {@link SimplifyDeep}
155
447
  @category Object
156
448
  */
157
- type Simplify<
158
- AnyType,
159
- Options extends SimplifyOptions = {},
160
- > = Flatten<AnyType> extends AnyType
161
- ? Flatten<AnyType, Options>
162
- : AnyType;
449
+ type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
163
450
 
164
451
  /**
165
- Remove any index signatures from the given object type, so that only explicitly defined properties remain.
452
+ Returns a boolean for whether the two given types are equal.
453
+
454
+ @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
455
+ @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
456
+
457
+ Use-cases:
458
+ - If you want to make a conditional branch based on the result of a comparison of two types.
459
+
460
+ @example
461
+ ```
462
+ import type {IsEqual} from 'type-fest';
463
+
464
+ // This type returns a boolean for whether the given array includes the given item.
465
+ // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
466
+ type Includes<Value extends readonly any[], Item> =
467
+ Value extends readonly [Value[0], ...infer rest]
468
+ ? IsEqual<Value[0], Item> extends true
469
+ ? true
470
+ : Includes<rest, Item>
471
+ : false;
472
+ ```
473
+
474
+ @category Type Guard
475
+ @category Utilities
476
+ */
477
+ type IsEqual<A, B> =
478
+ [A] extends [B]
479
+ ? [B] extends [A]
480
+ ? _IsEqual<A, B>
481
+ : false
482
+ : false;
483
+
484
+ // This version fails the `equalWrappedTupleIntersectionToBeNeverAndNeverExpanded` test in `test-d/is-equal.ts`.
485
+ type _IsEqual<A, B> =
486
+ (<G>() => G extends A & G | G ? 1 : 2) extends
487
+ (<G>() => G extends B & G | G ? 1 : 2)
488
+ ? true
489
+ : false;
490
+
491
+ /**
492
+ Omit any index signatures from the given object type, leaving only explicitly defined properties.
493
+
494
+ This is the counterpart of `PickIndexSignature`.
166
495
 
167
496
  Use-cases:
168
497
  - Remove overly permissive signatures from third-party types.
@@ -176,8 +505,9 @@ It relies on the fact that an empty object (`{}`) is assignable to an object wit
176
505
  ```
177
506
  const indexed: Record<string, unknown> = {}; // Allowed
178
507
 
508
+ // @ts-expect-error
179
509
  const keyed: Record<'foo', unknown> = {}; // Error
180
- // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
510
+ // TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
181
511
  ```
182
512
 
183
513
  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:
@@ -186,178 +516,455 @@ Instead of causing a type error like the above, you can also use a [conditional
186
516
  type Indexed = {} extends Record<string, unknown>
187
517
  ? '✅ `{}` is assignable to `Record<string, unknown>`'
188
518
  : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
189
- // => '✅ `{}` is assignable to `Record<string, unknown>`'
519
+
520
+ type IndexedResult = Indexed;
521
+ //=> '✅ `{}` is assignable to `Record<string, unknown>`'
190
522
 
191
523
  type Keyed = {} extends Record<'foo' | 'bar', unknown>
192
- ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
193
- : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
194
- // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
524
+ ? '✅ `{}` is assignable to `Record<\'foo\' | \'bar\', unknown>`'
525
+ : '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`';
526
+
527
+ type KeyedResult = Keyed;
528
+ //=> '❌ `{}` is NOT assignable to `Record<\'foo\' | \'bar\', unknown>`'
195
529
  ```
196
530
 
197
531
  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`...
198
532
 
199
533
  ```
200
- import type {RemoveIndexSignature} from 'type-fest';
201
-
202
- type RemoveIndexSignature<ObjectType> = {
534
+ type OmitIndexSignature<ObjectType> = {
203
535
  [KeyType in keyof ObjectType // Map each key of `ObjectType`...
204
- ]: ObjectType[KeyType]; // ...to its original value, i.e. `RemoveIndexSignature<Foo> == Foo`.
536
+ ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
205
537
  };
206
538
  ```
207
539
 
208
540
  ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
209
541
 
210
542
  ```
211
- import type {RemoveIndexSignature} from 'type-fest';
212
-
213
- type RemoveIndexSignature<ObjectType> = {
543
+ type OmitIndexSignature<ObjectType> = {
214
544
  [KeyType in keyof ObjectType
215
- // Is `{}` assignable to `Record<KeyType, unknown>`?
216
- as {} extends Record<KeyType, unknown>
217
- ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
218
- : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
545
+ // Is `{}` assignable to `Record<KeyType, unknown>`?
546
+ as {} extends Record<KeyType, unknown>
547
+ ? never // ✅ `{}` is assignable to `Record<KeyType, unknown>`
548
+ : KeyType // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
219
549
  ]: ObjectType[KeyType];
220
550
  };
221
551
  ```
222
552
 
223
553
  If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
224
554
 
225
- ```
226
- import type {RemoveIndexSignature} from 'type-fest';
227
-
228
- type RemoveIndexSignature<ObjectType> = {
229
- [KeyType in keyof ObjectType
230
- as {} extends Record<KeyType, unknown>
231
- ? never // => Remove this `KeyType`.
232
- : KeyType // => Keep this `KeyType` as it is.
233
- ]: ObjectType[KeyType];
234
- };
235
- ```
236
-
237
555
  @example
238
556
  ```
239
- import type {RemoveIndexSignature} from 'type-fest';
557
+ import type {OmitIndexSignature} from 'type-fest';
240
558
 
241
- interface Example {
559
+ type Example = {
242
560
  // These index signatures will be removed.
243
- [x: string]: any
244
- [x: number]: any
245
- [x: symbol]: any
246
- [x: `head-${string}`]: string
247
- [x: `${string}-tail`]: string
248
- [x: `head-${string}-tail`]: string
249
- [x: `${bigint}`]: string
250
- [x: `embedded-${number}`]: string
561
+ [x: string]: any;
562
+ [x: number]: any;
563
+ [x: symbol]: any;
564
+ [x: `head-${string}`]: string;
565
+ [x: `${string}-tail`]: string;
566
+ [x: `head-${string}-tail`]: string;
567
+ [x: `${bigint}`]: string;
568
+ [x: `embedded-${number}`]: string;
251
569
 
252
570
  // These explicitly defined keys will remain.
253
571
  foo: 'bar';
254
572
  qux?: 'baz';
255
- }
573
+ };
256
574
 
257
- type ExampleWithoutIndexSignatures = RemoveIndexSignature<Example>;
258
- // => { foo: 'bar'; qux?: 'baz' | undefined; }
575
+ type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
576
+ //=> {foo: 'bar'; qux?: 'baz'}
259
577
  ```
260
578
 
579
+ @see {@link PickIndexSignature}
261
580
  @category Object
262
581
  */
263
- type RemoveIndexSignature<ObjectType> = {
582
+ type OmitIndexSignature<ObjectType> = {
264
583
  [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
265
584
  ? never
266
585
  : KeyType]: ObjectType[KeyType];
267
586
  };
268
587
 
269
588
  /**
270
- Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type.
589
+ Pick only index signatures from the given object type, leaving out all explicitly defined properties.
271
590
 
272
- Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional.
591
+ This is the counterpart of `OmitIndexSignature`.
273
592
 
274
593
  @example
275
594
  ```
276
- import type {SetOptional} from 'type-fest';
595
+ import type {PickIndexSignature} from 'type-fest';
596
+
597
+ declare const symbolKey: unique symbol;
598
+
599
+ type Example = {
600
+ // These index signatures will remain.
601
+ [x: string]: unknown;
602
+ [x: number]: unknown;
603
+ [x: symbol]: unknown;
604
+ [x: `head-${string}`]: string;
605
+ [x: `${string}-tail`]: string;
606
+ [x: `head-${string}-tail`]: string;
607
+ [x: `${bigint}`]: string;
608
+ [x: `embedded-${number}`]: string;
609
+
610
+ // These explicitly defined keys will be removed.
611
+ ['kebab-case-key']: string;
612
+ [symbolKey]: string;
613
+ foo: 'bar';
614
+ qux?: 'baz';
615
+ };
616
+
617
+ type ExampleIndexSignature = PickIndexSignature<Example>;
618
+ // {
619
+ // [x: string]: unknown;
620
+ // [x: number]: unknown;
621
+ // [x: symbol]: unknown;
622
+ // [x: `head-${string}`]: string;
623
+ // [x: `${string}-tail`]: string;
624
+ // [x: `head-${string}-tail`]: string;
625
+ // [x: `${bigint}`]: string;
626
+ // [x: `embedded-${number}`]: string;
627
+ // }
628
+ ```
629
+
630
+ @see {@link OmitIndexSignature}
631
+ @category Object
632
+ */
633
+ type PickIndexSignature<ObjectType> = {
634
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
635
+ ? KeyType
636
+ : never]: ObjectType[KeyType];
637
+ };
638
+
639
+ // Merges two objects without worrying about index signatures.
640
+ type SimpleMerge<Destination, Source> = Simplify<{
641
+ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
642
+ } & Source>;
643
+
644
+ /**
645
+ Merge two types into a new type. Keys of the second type overrides keys of the first type.
646
+
647
+ 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`.
648
+
649
+ @example
650
+ ```
651
+ import type {Merge} from 'type-fest';
277
652
 
278
653
  type Foo = {
279
- a: number;
280
- b?: string;
654
+ a: string;
655
+ b: number;
656
+ };
657
+
658
+ type Bar = {
659
+ a: number; // Conflicts with Foo['a']
281
660
  c: boolean;
282
- }
661
+ };
283
662
 
284
- type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
285
- // type SomeOptional = {
286
- // a: number;
287
- // b?: string; // Was already optional and still is.
288
- // c?: boolean; // Is now optional.
663
+ // With `&`, `a` becomes `string & number` which is `never`. Not what you want.
664
+ type WithIntersection = (Foo & Bar)['a'];
665
+ //=> never
666
+
667
+ // With `Merge`, `a` is cleanly overridden to `number`.
668
+ type WithMerge = Merge<Foo, Bar>['a'];
669
+ //=> number
670
+ ```
671
+
672
+ @example
673
+ ```
674
+ import type {Merge} from 'type-fest';
675
+
676
+ type Foo = {
677
+ [x: string]: unknown;
678
+ [x: number]: unknown;
679
+ foo: string;
680
+ bar: symbol;
681
+ };
682
+
683
+ type Bar = {
684
+ [x: number]: number;
685
+ [x: symbol]: unknown;
686
+ bar: Date;
687
+ baz: boolean;
688
+ };
689
+
690
+ export type FooBar = Merge<Foo, Bar>;
691
+ //=> {
692
+ // [x: string]: unknown;
693
+ // [x: number]: number;
694
+ // [x: symbol]: unknown;
695
+ // foo: string;
696
+ // bar: Date;
697
+ // baz: boolean;
289
698
  // }
290
699
  ```
291
700
 
701
+ 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.
702
+
703
+ @see {@link ObjectMerge}
292
704
  @category Object
293
705
  */
294
- type SetOptional<BaseType, Keys extends keyof BaseType> =
706
+ type Merge<Destination, Source> =
707
+ Destination extends unknown // For distributing `Destination`
708
+ ? Source extends unknown // For distributing `Source`
709
+ ? If<IsEqual<Destination, Source>, Destination, _Merge<Destination, Source>>
710
+ : never // Should never happen
711
+ : never; // Should never happen
712
+
713
+ type _Merge<Destination, Source> =
295
714
  Simplify<
296
- // Pick just the keys that are readonly from the base type.
297
- Except<BaseType, Keys> &
298
- // Pick the keys that should be mutable from the base type and make them mutable.
299
- Partial<Pick<BaseType, Keys>>
715
+ SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
716
+ & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
300
717
  >;
301
718
 
302
719
  /**
303
- Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
720
+ Works similar to the built-in `Pick` utility type, except for the following differences:
721
+ - Distributes over union types and allows picking keys from any member of the union type.
722
+ - Primitives types are returned as-is.
723
+ - Picks all keys if `Keys` is `any`.
724
+ - Doesn't pick `number` from a `string` index signature.
304
725
 
305
- Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
726
+ @example
727
+ ```
728
+ type ImageUpload = {
729
+ url: string;
730
+ size: number;
731
+ thumbnailUrl: string;
732
+ };
733
+
734
+ type VideoUpload = {
735
+ url: string;
736
+ duration: number;
737
+ encodingFormat: string;
738
+ };
739
+
740
+ // Distributes over union types and allows picking keys from any member of the union type
741
+ type MediaDisplay = HomomorphicPick<ImageUpload | VideoUpload, "url" | "size" | "duration">;
742
+ //=> {url: string; size: number} | {url: string; duration: number}
743
+
744
+ // Primitive types are returned as-is
745
+ type Primitive = HomomorphicPick<string | number, 'toUpperCase' | 'toString'>;
746
+ //=> string | number
747
+
748
+ // Picks all keys if `Keys` is `any`
749
+ type Any = HomomorphicPick<{a: 1; b: 2} | {c: 3}, any>;
750
+ //=> {a: 1; b: 2} | {c: 3}
751
+
752
+ // Doesn't pick `number` from a `string` index signature
753
+ type IndexSignature = HomomorphicPick<{[k: string]: unknown}, number>;
754
+ //=> {}
755
+ */
756
+ type HomomorphicPick<T, Keys extends KeysOfUnion<T>> = {
757
+ [P in keyof T as Extract<P, Keys>]: T[P]
758
+ };
759
+
760
+ /**
761
+ Merges user specified options with default options.
306
762
 
307
763
  @example
308
764
  ```
309
- import type {UnionToIntersection} from 'type-fest';
765
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
766
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
767
+ type SpecifiedOptions = {leavesOnly: true};
310
768
 
311
- type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
769
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
770
+ //=> {maxRecursionDepth: 10; leavesOnly: true}
771
+ ```
312
772
 
313
- type Intersection = UnionToIntersection<Union>;
314
- //=> {the(): void; great(arg: string): void; escape: boolean};
773
+ @example
315
774
  ```
775
+ // Complains if default values are not provided for optional options
316
776
 
317
- A more applicable example which could make its way into your library code follows.
777
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
778
+ type DefaultPathsOptions = {maxRecursionDepth: 10};
779
+ type SpecifiedOptions = {};
780
+
781
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
782
+ // ~~~~~~~~~~~~~~~~~~~
783
+ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
784
+ ```
318
785
 
319
786
  @example
320
787
  ```
321
- import type {UnionToIntersection} from 'type-fest';
788
+ // Complains if an option's default type does not conform to the expected type
322
789
 
323
- class CommandOne {
324
- commands: {
325
- a1: () => undefined,
326
- b1: () => undefined,
327
- }
328
- }
790
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
791
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
792
+ type SpecifiedOptions = {};
329
793
 
330
- class CommandTwo {
331
- commands: {
332
- a2: (argA: string) => undefined,
333
- b2: (argB: string) => undefined,
334
- }
335
- }
794
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
795
+ // ~~~~~~~~~~~~~~~~~~~
796
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
797
+ ```
336
798
 
337
- const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands);
338
- type Union = typeof union;
339
- //=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void}
799
+ @example
800
+ ```
801
+ // Complains if an option's specified type does not conform to the expected type
340
802
 
341
- type Intersection = UnionToIntersection<Union>;
342
- //=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void}
803
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
804
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
805
+ type SpecifiedOptions = {leavesOnly: 'yes'};
806
+
807
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
808
+ // ~~~~~~~~~~~~~~~~
809
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
343
810
  ```
811
+ */
812
+ type ApplyDefaultOptions<
813
+ Options extends object,
814
+ Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
815
+ SpecifiedOptions extends Options,
816
+ > =
817
+ If<IsAny<SpecifiedOptions>, Defaults,
818
+ If<IsNever<SpecifiedOptions>, Defaults,
819
+ Simplify<Merge<Defaults, {
820
+ [Key in keyof SpecifiedOptions
821
+ as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key
822
+ ]: SpecifiedOptions[Key]
823
+ }> & Required<Options>>>>;
344
824
 
345
- @category Type
825
+ /**
826
+ Filter out keys from an object.
827
+
828
+ Returns `never` if `Exclude` is strictly equal to `Key`.
829
+ Returns `never` if `Key` extends `Exclude`.
830
+ Returns `Key` otherwise.
831
+
832
+ @example
833
+ ```
834
+ type Filtered = Filter<'foo', 'foo'>;
835
+ //=> never
836
+ ```
837
+
838
+ @example
839
+ ```
840
+ type Filtered = Filter<'bar', string>;
841
+ //=> never
842
+ ```
843
+
844
+ @example
845
+ ```
846
+ type Filtered = Filter<'bar', 'foo'>;
847
+ //=> 'bar'
848
+ ```
849
+
850
+ @see {Except}
346
851
  */
347
- type UnionToIntersection<Union> = (
348
- // `extends unknown` is always going to be the case and is used to convert the
349
- // `Union` into a [distributive conditional
350
- // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
351
- Union extends unknown
352
- // The union type is used as the only argument to a function since the union
353
- // of function arguments is an intersection.
354
- ? (distributedUnion: Union) => void
355
- // This won't happen.
356
- : never
357
- // Infer the `Intersection` type since TypeScript represents the positional
358
- // arguments of unions of functions as an intersection of the union.
359
- ) extends ((mergedIntersection: infer Intersection) => void)
360
- ? Intersection
852
+ type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType);
853
+
854
+ type ExceptOptions = {
855
+ /**
856
+ Disallow assigning non-specified properties.
857
+
858
+ Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.
859
+
860
+ @default false
861
+ */
862
+ requireExactProps?: boolean;
863
+ };
864
+
865
+ type DefaultExceptOptions = {
866
+ requireExactProps: false;
867
+ };
868
+
869
+ /**
870
+ Create a type from an object type without certain keys.
871
+
872
+ We recommend setting the `requireExactProps` option to `true`.
873
+
874
+ This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
875
+
876
+ This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
877
+
878
+ @example
879
+ ```
880
+ import type {Except} from 'type-fest';
881
+
882
+ type Foo = {
883
+ a: number;
884
+ b: string;
885
+ };
886
+
887
+ type FooWithoutA = Except<Foo, 'a'>;
888
+ //=> {b: string}
889
+
890
+ // @ts-expect-error
891
+ const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
892
+ // errors: 'a' does not exist in type '{ b: string; }'
893
+
894
+ type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>;
895
+ //=> {a: number} & Partial<Record<'b', never>>
896
+
897
+ // @ts-expect-error
898
+ const fooWithoutB: FooWithoutB = {a: 1, b: '2'};
899
+ // errors at 'b': Type 'string' is not assignable to type 'undefined'.
900
+
901
+ // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures.
902
+
903
+ // Consider the following example:
904
+
905
+ type UserData = {
906
+ [metadata: string]: string;
907
+ email: string;
908
+ name: string;
909
+ role: 'admin' | 'user';
910
+ };
911
+
912
+ // `Omit` clearly doesn't behave as expected in this case:
913
+ type PostPayload = Omit<UserData, 'email'>;
914
+ //=> {[x: string]: string; [x: number]: string}
915
+
916
+ // In situations like this, `Except` works better.
917
+ // It simply removes the `email` key while preserving all the other keys.
918
+ type PostPayloadFixed = Except<UserData, 'email'>;
919
+ //=> {[x: string]: string; name: string; role: 'admin' | 'user'}
920
+ ```
921
+
922
+ @category Object
923
+ */
924
+ type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {}> =
925
+ _Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>;
926
+
927
+ type _Except<ObjectType, KeysType extends keyof ObjectType, Options extends Required<ExceptOptions>> = {
928
+ [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
929
+ } & (Options['requireExactProps'] extends true
930
+ ? Partial<Record<KeysType, never>>
931
+ : {});
932
+
933
+ /**
934
+ Create a type that makes the given keys optional, while keeping the remaining keys as is.
935
+
936
+ Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional.
937
+
938
+ @example
939
+ ```
940
+ import type {SetOptional} from 'type-fest';
941
+
942
+ type Foo = {
943
+ a: number;
944
+ b?: string;
945
+ c: boolean;
946
+ };
947
+
948
+ type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
949
+ //=> {a: number; b?: string; c?: boolean}
950
+ ```
951
+
952
+ @category Object
953
+ */
954
+ type SetOptional<BaseType, Keys extends keyof BaseType> =
955
+ (BaseType extends (...arguments_: never) => any
956
+ ? (...arguments_: Parameters<BaseType>) => ReturnType<BaseType>
957
+ : unknown)
958
+ & _SetOptional<BaseType, Keys>;
959
+
960
+ type _SetOptional<BaseType, Keys extends keyof BaseType> =
961
+ BaseType extends unknown // To distribute `BaseType` when it's a union type.
962
+ ? Simplify<
963
+ // Pick just the keys that are readonly from the base type.
964
+ Except<BaseType, Keys>
965
+ // Pick the keys that should be mutable from the base type and make them mutable.
966
+ & Partial<HomomorphicPick<BaseType, Keys>>
967
+ >
361
968
  : never;
362
969
 
363
970
  interface ReactRenderer extends WebRenderer {
@@ -391,7 +998,7 @@ type AddMocks<TArgs, DefaultArgs> = Simplify<{
391
998
 
392
999
  /** Extracts and unions all args types from an array of decorators. */
393
1000
  type DecoratorsArgs<TRenderer extends Renderer, Decorators> = UnionToIntersection<Decorators extends DecoratorFunction<TRenderer, infer TArgs> ? TArgs : unknown>;
394
- type InferArgs<TArgs, T, Decorators> = Simplify<TArgs & Simplify<RemoveIndexSignature<DecoratorsArgs<ReactTypes & T, Decorators>>>>;
1001
+ type InferArgs<TArgs, T, Decorators> = Simplify<TArgs & Simplify<OmitIndexSignature<DecoratorsArgs<ReactTypes & T, Decorators>>>>;
395
1002
  type InferReactTypes<T, TArgs, Decorators> = ReactTypes & T & {
396
1003
  args: Simplify<InferArgs<TArgs, T, Decorators>>;
397
1004
  };