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