@storybook/react 10.5.2 → 10.6.0-alpha.1

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
@@ -1,1154 +1,2 @@
1
- import { ComponentType, JSX } from 'react';
2
- import { PreviewAddon, InferTypes, AddonTypes, Preview, Meta, Story } from 'storybook/internal/csf';
3
- import { WebRenderer, Canvas, ProjectAnnotations, Args, DecoratorFunction, ArgsStoryFn, ComponentAnnotations, StoryAnnotations, Renderer } from 'storybook/internal/types';
4
- import { RootOptions } from 'react-dom/client';
5
-
6
- /**
7
- Convert a union type to an intersection type.
8
-
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
22
- */
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;
39
-
40
- /**
41
- Create a union of all keys from a given type, even those exclusive to specific union members.
42
-
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
46
-
47
- @example
48
- ```
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'
73
- ```
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
-
88
- @example
89
- ```
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
104
- ```
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
-
116
- @example
117
- ```
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
146
- ```
147
-
148
- @category Type Guard
149
- @category Utilities
150
- */
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;
158
-
159
- /**
160
- Extract all optional keys from the given type.
161
-
162
- This is useful when you want to create a new type that contains different type values for the optional keys only.
163
-
164
- @example
165
- ```
166
- import type {OptionalKeysOf, Except} from 'type-fest';
167
-
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;
178
- };
179
-
180
- const update1: UpdateOperation<User> = {
181
- name: 'Alice',
182
- };
183
-
184
- const update2: UpdateOperation<User> = {
185
- name: 'Bob',
186
- luckyNumber: REMOVE_FIELD,
187
- };
188
- ```
189
-
190
- @category Utilities
191
- */
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;
220
- };
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
-
237
- /**
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
289
- */
290
- type IsNever<T> = [T] extends [never] ? true : false;
291
-
292
- /**
293
- An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
294
-
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;
390
-
391
- /**
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.
393
-
394
- @example
395
- ```
396
- import type {Simplify} from 'type-fest';
397
-
398
- type PositionProps = {
399
- top: number;
400
- left: number;
401
- };
402
-
403
- type SizeProps = {
404
- width: number;
405
- height: number;
406
- };
407
-
408
- // In your editor, hovering over `Props` will show a flattened object with all the properties.
409
- type Props = Simplify<PositionProps & SizeProps>;
410
- ```
411
-
412
- 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.
413
-
414
- 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`.
415
-
416
- @example
417
- ```
418
- import type {Simplify} from 'type-fest';
419
-
420
- interface SomeInterface {
421
- foo: number;
422
- bar?: string;
423
- baz: number | undefined;
424
- }
425
-
426
- type SomeType = {
427
- foo: number;
428
- bar?: string;
429
- baz: number | undefined;
430
- };
431
-
432
- const literal = {foo: 123, bar: 'hello', baz: 456};
433
- const someType: SomeType = literal;
434
- const someInterface: SomeInterface = literal;
435
-
436
- declare function fn(object: Record<string, unknown>): void;
437
-
438
- fn(literal); // Good: literal object type is sealed
439
- fn(someType); // Good: type is sealed
440
- // @ts-expect-error
441
- fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
442
- fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
443
- ```
444
-
445
- @link https://github.com/microsoft/TypeScript/issues/15300
446
- @see {@link SimplifyDeep}
447
- @category Object
448
- */
449
- type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
450
-
451
- /**
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`.
495
-
496
- Use-cases:
497
- - Remove overly permissive signatures from third-party types.
498
-
499
- This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
500
-
501
- It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
502
-
503
- (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
504
-
505
- ```
506
- const indexed: Record<string, unknown> = {}; // Allowed
507
-
508
- // @ts-expect-error
509
- const keyed: Record<'foo', unknown> = {}; // Error
510
- // TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
511
- ```
512
-
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:
514
-
515
- ```
516
- type Indexed = {} extends Record<string, unknown>
517
- ? '✅ `{}` is assignable to `Record<string, unknown>`'
518
- : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
519
-
520
- type IndexedResult = Indexed;
521
- //=> '✅ `{}` is assignable to `Record<string, unknown>`'
522
-
523
- type Keyed = {} extends 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>`'
529
- ```
530
-
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`...
532
-
533
- ```
534
- type OmitIndexSignature<ObjectType> = {
535
- [KeyType in keyof ObjectType // Map each key of `ObjectType`...
536
- ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
537
- };
538
- ```
539
-
540
- ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
541
-
542
- ```
543
- type OmitIndexSignature<ObjectType> = {
544
- [KeyType in keyof ObjectType
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>`
549
- ]: ObjectType[KeyType];
550
- };
551
- ```
552
-
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.
554
-
555
- @example
556
- ```
557
- import type {OmitIndexSignature} from 'type-fest';
558
-
559
- type Example = {
560
- // These index signatures will be removed.
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;
569
-
570
- // These explicitly defined keys will remain.
571
- foo: 'bar';
572
- qux?: 'baz';
573
- };
574
-
575
- type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
576
- //=> {foo: 'bar'; qux?: 'baz'}
577
- ```
578
-
579
- @see {@link PickIndexSignature}
580
- @category Object
581
- */
582
- type OmitIndexSignature<ObjectType> = {
583
- [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
584
- ? never
585
- : KeyType]: ObjectType[KeyType];
586
- };
587
-
588
- /**
589
- Pick only index signatures from the given object type, leaving out all explicitly defined properties.
590
-
591
- This is the counterpart of `OmitIndexSignature`.
592
-
593
- @example
594
- ```
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';
652
-
653
- type Foo = {
654
- a: string;
655
- b: number;
656
- };
657
-
658
- type Bar = {
659
- a: number; // Conflicts with Foo['a']
660
- c: boolean;
661
- };
662
-
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;
698
- // }
699
- ```
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}
704
- @category Object
705
- */
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> =
714
- Simplify<
715
- SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
716
- & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
717
- >;
718
-
719
- /**
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.
725
-
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.
762
-
763
- @example
764
- ```
765
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
766
- type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
767
- type SpecifiedOptions = {leavesOnly: true};
768
-
769
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
770
- //=> {maxRecursionDepth: 10; leavesOnly: true}
771
- ```
772
-
773
- @example
774
- ```
775
- // Complains if default values are not provided for optional options
776
-
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
- ```
785
-
786
- @example
787
- ```
788
- // Complains if an option's default type does not conform to the expected type
789
-
790
- type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
791
- type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
792
- type SpecifiedOptions = {};
793
-
794
- type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
795
- // ~~~~~~~~~~~~~~~~~~~
796
- // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
797
- ```
798
-
799
- @example
800
- ```
801
- // Complains if an option's specified type does not conform to the expected type
802
-
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'.
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>>>>;
824
-
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}
851
- */
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
- >
968
- : never;
969
-
970
- interface ReactRenderer extends WebRenderer {
971
- component: ComponentType<this['T']>;
972
- storyResult: StoryFnReactReturnType;
973
- mount: (ui?: JSX.Element) => Promise<Canvas>;
974
- }
975
- interface ReactParameters {
976
- /** React renderer configuration */
977
- react?: {
978
- /**
979
- * Whether to enable React Server Components
980
- *
981
- * @see https://storybook.js.org/docs/get-started/frameworks/nextjs#react-server-components-rsc
982
- */
983
- rsc?: boolean;
984
- /** Options passed to React root creation */
985
- rootOptions?: RootOptions;
986
- };
987
- }
988
- interface ReactTypes extends ReactRenderer {
989
- parameters: ReactParameters;
990
- }
991
- type StoryFnReactReturnType = JSX.Element;
992
-
993
- type AddMocks<TArgs, DefaultArgs> = Simplify<{
994
- [T in keyof TArgs]: T extends keyof DefaultArgs ? DefaultArgs[T] extends (...args: any) => any & {
995
- mock: {};
996
- } ? DefaultArgs[T] : TArgs[T] : TArgs[T];
997
- }>;
998
-
999
- /** Extracts and unions all args types from an array of decorators. */
1000
- type DecoratorsArgs<TRenderer extends Renderer, Decorators> = UnionToIntersection<Decorators extends DecoratorFunction<TRenderer, infer TArgs> ? TArgs : unknown>;
1001
- type InferArgs<TArgs, T, Decorators> = Simplify<TArgs & Simplify<OmitIndexSignature<DecoratorsArgs<ReactTypes & T, Decorators>>>>;
1002
- type InferReactTypes<T, TArgs, Decorators> = ReactTypes & T & {
1003
- args: Simplify<InferArgs<TArgs, T, Decorators>>;
1004
- };
1005
- /**
1006
- * Creates a React-specific preview configuration with CSF factories support.
1007
- *
1008
- * This function wraps the base `definePreview` and adds React-specific annotations for rendering
1009
- * and documentation. It returns a `ReactPreview` that provides type-safe `meta()` and `story()`
1010
- * factory methods.
1011
- *
1012
- * @example
1013
- *
1014
- * ```ts
1015
- * // .storybook/preview.ts
1016
- * import { definePreview } from '@storybook/react';
1017
- *
1018
- * export const preview = definePreview({
1019
- * addons: [],
1020
- * parameters: { layout: 'centered' },
1021
- * });
1022
- * ```
1023
- */
1024
- declare function __definePreview<Addons extends PreviewAddon<never>[]>(input: {
1025
- addons: Addons;
1026
- } & ProjectAnnotations<ReactTypes & InferTypes<Addons>>): ReactPreview<ReactTypes & InferTypes<Addons>>;
1027
- /**
1028
- * React-specific Preview interface that provides type-safe CSF factory methods.
1029
- *
1030
- * Use `preview.meta()` to create a meta configuration for a component, and then `meta.story()` to
1031
- * create individual stories. The type system will infer args from the component props, decorators,
1032
- * and any addon types.
1033
- *
1034
- * @example
1035
- *
1036
- * ```ts
1037
- * const meta = preview.meta({ component: Button });
1038
- * export const Primary = meta.story({ args: { label: 'Click me' } });
1039
- * ```
1040
- */
1041
- /** @ts-expect-error We cannot implement the meta faithfully here, but that is okay. */
1042
- interface ReactPreview<T extends AddonTypes> extends Preview<ReactTypes & T> {
1043
- /**
1044
- * Narrows the type of the preview to include additional type information. This is useful when you
1045
- * need to add args that aren't inferred from the component.
1046
- *
1047
- * @example
1048
- *
1049
- * ```ts
1050
- * const meta = preview.type<{ args: { theme: 'light' | 'dark' } }>().meta({
1051
- * component: Button,
1052
- * });
1053
- * ```
1054
- */
1055
- type<R>(): ReactPreview<T & R>;
1056
- meta<TArgs extends Args, Decorators extends DecoratorFunction<ReactTypes & T, any>, TMetaArgs extends Partial<TArgs & T['args']>>(meta: {
1057
- render?: ArgsStoryFn<ReactTypes & T, TArgs & T['args']>;
1058
- component?: ComponentType<TArgs>;
1059
- decorators?: Decorators | Decorators[];
1060
- args?: TMetaArgs;
1061
- } & Omit<ComponentAnnotations<ReactTypes & T, TArgs>, 'decorators' | 'component' | 'args' | 'render'>): ReactMeta<InferReactTypes<T, TArgs, Decorators>, Omit<ComponentAnnotations<InferReactTypes<T, TArgs, Decorators>>, 'args'> & {
1062
- args: Partial<TArgs> extends TMetaArgs ? {} : TMetaArgs;
1063
- }>;
1064
- }
1065
- /**
1066
- * React-specific Meta interface returned by `preview.meta()`.
1067
- *
1068
- * Provides the `story()` method to create individual stories with proper type inference. Args
1069
- * provided in meta become optional in stories, while missing required args must be provided at the
1070
- * story level.
1071
- */
1072
- interface ReactMeta<T extends ReactTypes, MetaInput extends ComponentAnnotations<T>>
1073
- /** @ts-expect-error ReactMeta requires two type parameters, but Meta's constraints differ */
1074
- extends Meta<T, MetaInput> {
1075
- /**
1076
- * Creates a story with a custom render function that takes no args.
1077
- *
1078
- * This overload allows you to define a story using just a render function or an object with a
1079
- * render function that doesn't depend on args. Since the render function doesn't use args, no
1080
- * args need to be provided regardless of what's required by the component.
1081
- *
1082
- * @example
1083
- *
1084
- * ```ts
1085
- * // Using just a render function
1086
- * export const CustomRender = meta.story(() => <div>Custom content</div>);
1087
- *
1088
- * // Using an object with render
1089
- * export const WithRender = meta.story({
1090
- * render: () => <MyComponent prop="static" />,
1091
- * });
1092
- * ```
1093
- */
1094
- story<TInput extends (() => ReactTypes['storyResult']) | (StoryAnnotations<T, T['args']> & {
1095
- render: () => ReactTypes['storyResult'];
1096
- })>(story: TInput): ReactStory<T, TInput extends () => ReactTypes['storyResult'] ? {
1097
- render: TInput;
1098
- } : TInput>;
1099
- /**
1100
- * Creates a story with custom configuration including args, decorators, or other annotations.
1101
- *
1102
- * This is the primary overload for defining stories. Args that were already provided in meta
1103
- * become optional, while any remaining required args must be specified here.
1104
- *
1105
- * @example
1106
- *
1107
- * ```ts
1108
- * // Provide required args not in meta
1109
- * export const Primary = meta.story({
1110
- * args: { label: 'Click me', disabled: false },
1111
- * });
1112
- *
1113
- * // Override meta args and add story-specific configuration
1114
- * export const Disabled = meta.story({
1115
- * args: { disabled: true },
1116
- * decorators: [withCustomWrapper],
1117
- * });
1118
- * ```
1119
- */
1120
- story<TInput extends Simplify<StoryAnnotations<T, AddMocks<T['args'], MetaInput['args']>, SetOptional<T['args'], keyof T['args'] & keyof MetaInput['args']>>>>(story: TInput
1121
- /** @ts-expect-error hard */
1122
- ): ReactStory<T, TInput>;
1123
- /**
1124
- * Creates a story with no additional configuration.
1125
- *
1126
- * This overload is only available when all required args have been provided in meta. The
1127
- * conditional type `Partial<T['args']> extends SetOptional<...>` checks if the remaining required
1128
- * args (after accounting for args provided in meta) are all optional. If so, the function accepts
1129
- * zero arguments `[]`. Otherwise, it requires `[never]` which makes this overload unmatchable,
1130
- * forcing the user to provide args.
1131
- *
1132
- * @example
1133
- *
1134
- * ```ts
1135
- * // When meta provides all required args, story() can be called with no arguments
1136
- * const meta = preview.meta({ component: Button, args: { label: 'Hi', disabled: false } });
1137
- * export const Default = meta.story(); // Valid - all args provided in meta
1138
- * ```
1139
- */
1140
- story(..._args: Partial<T['args']> extends SetOptional<T['args'], keyof T['args'] & keyof MetaInput['args']> ? [] : [never]): ReactStory<T, {}>;
1141
- }
1142
- /**
1143
- * React-specific Story interface returned by `meta.story()`.
1144
- *
1145
- * Represents a single story with its configuration and provides access to the composed story for
1146
- * testing via `story.run()`.
1147
- *
1148
- * Also includes a `Component` property for portable story compatibility.
1149
- */
1150
- interface ReactStory<T extends ReactTypes, TInput extends StoryAnnotations<T, T['args']>> extends Story<T, TInput> {
1151
- Component: ComponentType<Partial<T['args']>>;
1152
- }
1153
-
1154
- export { type ReactMeta, type ReactPreview, type ReactStory, __definePreview };
1
+ import { i as __definePreview, n as ReactPreview, r as ReactStory, t as ReactMeta } from "./chunk-ojHmM-yX.js";
2
+ export { ReactMeta, ReactPreview, ReactStory, __definePreview };