type-fest 2.17.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -15,6 +15,7 @@ export {RequireExactlyOne} from './source/require-exactly-one';
15
15
  export {RequireAllOrNone} from './source/require-all-or-none';
16
16
  export {RemoveIndexSignature} from './source/remove-index-signature';
17
17
  export {PartialDeep, PartialDeepOptions} from './source/partial-deep';
18
+ export {PartialOnUndefinedDeep, PartialOnUndefinedDeepOptions} from './source/partial-on-undefined-deep';
18
19
  export {ReadonlyDeep} from './source/readonly-deep';
19
20
  export {LiteralUnion} from './source/literal-union';
20
21
  export {Promisable} from './source/promisable';
@@ -22,6 +23,7 @@ export {Opaque, UnwrapOpaque} from './source/opaque';
22
23
  export {InvariantOf} from './source/invariant-of';
23
24
  export {SetOptional} from './source/set-optional';
24
25
  export {SetRequired} from './source/set-required';
26
+ export {SetNonNullable} from './source/set-non-nullable';
25
27
  export {ValueOf} from './source/value-of';
26
28
  export {PromiseValue} from './source/promise-value';
27
29
  export {AsyncReturnType} from './source/async-return-type';
@@ -61,6 +63,7 @@ export {OptionalKeysOf} from './source/optional-keys-of';
61
63
  export {HasOptionalKeys} from './source/has-optional-keys';
62
64
  export {RequiredKeysOf} from './source/required-keys-of';
63
65
  export {HasRequiredKeys} from './source/has-required-keys';
66
+ export {Spread} from './source/spread';
64
67
 
65
68
  // Template literal types
66
69
  export {CamelCase} from './source/camel-case';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "type-fest",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "description": "A collection of essential TypeScript types",
5
5
  "license": "(MIT OR CC0-1.0)",
6
6
  "repository": "sindresorhus/type-fest",
package/readme.md CHANGED
@@ -40,41 +40,6 @@
40
40
  <br>
41
41
  <br>
42
42
  <br>
43
- <a href="https://neverinstall.com/spaces/devtools?utm_source=github&utm_medium=sponsor&utm_campaign=sindre#gh-light-mode-only">
44
- <div>
45
- <img src="https://sindresorhus.com/assets/thanks/neverinstall-logo-light.svg" width="200" alt="neverinstall">
46
- </div>
47
- <br>
48
- <b>All your favourite IDE's now available on the cloud</b>
49
- <div>
50
- <sub>
51
- Neverinstall gives you an uninterrupted development experience and improved accessibility,
52
- <br>
53
- allowing you to code faster, better and on-the-go on your favourite IDEs like
54
- <br>
55
- Android Studio, VS Code, Jupyter and PyCharm using your browser.
56
- </sub>
57
- </div>
58
- </a>
59
- <a href="https://neverinstall.com/spaces/devtools?utm_source=github&utm_medium=sponsor&utm_campaign=sindre#gh-dark-mode-only">
60
- <div>
61
- <img src="https://sindresorhus.com/assets/thanks/neverinstall-logo-dark.svg" width="200" alt="neverinstall">
62
- </div>
63
- <br>
64
- <b>All your favourite IDE's now available on the cloud</b>
65
- <div>
66
- <sub>
67
- Neverinstall gives you an uninterrupted development experience and improved accessibility,
68
- <br>
69
- allowing you to code faster, better and on-the-go on your favourite IDEs like
70
- <br>
71
- Android Studio, VS Code, Jupyter and PyCharm using your browser.
72
- </sub>
73
- </div>
74
- </a>
75
- <br>
76
- <br>
77
- <br>
78
43
  <a href="https://www.useanvil.com/?utm_source=sindresorhus#gh-light-mode-only">
79
44
  <div>
80
45
  <img src="https://sindresorhus.com/assets/thanks/anvil-logo-light.svg" width="200" alt="Anvil">
@@ -169,6 +134,7 @@ Click the type names for complete docs.
169
134
  - [`RequireAllOrNone`](source/require-all-or-none.d.ts) - Create a type that requires all of the given keys or none of the given keys.
170
135
  - [`RemoveIndexSignature`](source/remove-index-signature.d.ts) - Create a type that only has explicitly defined properties, absent of any index signatures.
171
136
  - [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) if you only need one level deep.
137
+ - [`PartialOnUndefinedDeep`](source/partial-on-undefined-deep.d.ts) - Create a deep version of another type where all keys accepting `undefined` type are set to optional.
172
138
  - [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) if you only need one level deep.
173
139
  - [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
174
140
  - [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
@@ -176,6 +142,7 @@ Click the type names for complete docs.
176
142
  - [`InvariantOf`](source/invariant-of.d.ts) - Create an [invariant type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance), which is a type that does not accept supertypes and subtypes.
177
143
  - [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
178
144
  - [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
145
+ - [`SetNonNullable`](source/set-non-nullable.d.ts) - Create a type that makes the given keys non-nullable.
179
146
  - [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from.
180
147
  - [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type.
181
148
  - [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type.
@@ -196,6 +163,7 @@ Click the type names for complete docs.
196
163
  - [`HasOptionalKeys`](source/has-optional-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any optional fields.
197
164
  - [`RequiredKeysOf`](source/required-keys-of.d.ts) - Extract all required keys from the given type.
198
165
  - [`HasRequiredKeys`](source/has-required-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any required fields.
166
+ - [`Spread`](source/spread.d.ts) - Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.
199
167
 
200
168
  ### JSON
201
169
 
package/source/exact.d.ts CHANGED
@@ -1,6 +1,29 @@
1
- import type {Primitive} from './primitive';
2
1
  import type {KeysOfUnion} from './internal';
3
2
 
3
+ /**
4
+ Extract the element of an array that also works for array union.
5
+
6
+ Returns `never` if T is not an array.
7
+
8
+ It creates a type-safe way to access the element type of `unknown` type.
9
+ */
10
+ type ArrayElement<T> = T extends readonly unknown[] ? T[0] : never;
11
+
12
+ /**
13
+ Extract the object field type if T is an object and K is a key of T, return `never` otherwise.
14
+
15
+ It creates a type-safe way to access the member type of `unknown` type.
16
+ */
17
+ type ObjectValue<T, K> = K extends keyof T ? T[K] : never;
18
+
19
+ /**
20
+ Create a type from `ParameterType` and `InputType` and change keys exclusive to `InputType` to `never`.
21
+ - Generate a list of keys that exists in `InputType` but not in `ParameterType`.
22
+ - Mark these excess keys as `never`.
23
+ */
24
+ type ExactObject<ParameterType, InputType> = {[Key in keyof ParameterType]: Exact<ParameterType[Key], ObjectValue<InputType, Key>>}
25
+ & Record<Exclude<keyof InputType, KeysOfUnion<ParameterType>>, never>;
26
+
4
27
  /**
5
28
  Create a type that does not allow extra properties, meaning it only allows properties that are explicitly declared.
6
29
 
@@ -41,11 +64,10 @@ onlyAcceptNameImproved(invalidInput); // Compilation error
41
64
 
42
65
  @category Utilities
43
66
  */
44
- export type Exact<ParameterType, InputType extends ParameterType> = ParameterType extends Primitive
45
- ? ParameterType
46
- /*
47
- Create a type from `ParameterType` and `InputType` and change keys exclusive to `InputType` to `never`.
48
- - Generate a list of keys that exists in `InputType` but not in `ParameterType`.
49
- - Mark these excess keys as `never`.
50
- */
51
- : {[Key in keyof ParameterType]: Exact<ParameterType[Key], InputType[Key]>} & Record<Exclude<keyof InputType, KeysOfUnion<ParameterType>>, never>;
67
+ export type Exact<ParameterType, InputType> =
68
+ // Convert union of array to array of union: A[] & B[] => (A & B)[]
69
+ ParameterType extends unknown[] ? Array<Exact<ArrayElement<ParameterType>, ArrayElement<InputType>>>
70
+ // In TypeScript, Array is a subtype of ReadonlyArray, so always test Array before ReadonlyArray.
71
+ : ParameterType extends readonly unknown[] ? ReadonlyArray<Exact<ArrayElement<ParameterType>, ArrayElement<InputType>>>
72
+ : ParameterType extends object ? ExactObject<ParameterType, InputType>
73
+ : ParameterType;
@@ -67,25 +67,24 @@ type Jsonify<T> =
67
67
  // Note: The use of tuples in this first condition side-steps distributive conditional types
68
68
  // (see https://github.com/microsoft/TypeScript/issues/29368#issuecomment-453529532)
69
69
  [Extract<T, NotJsonable | bigint>] extends [never]
70
- ? T extends PositiveInfinity | NegativeInfinity ? null
71
- : T extends JsonPrimitive
72
- ? T // Primitive is acceptable
73
- : T extends Number ? number
74
- : T extends String ? string
75
- : T extends Boolean ? boolean
76
- : T extends Map<any, any> | Set<any> ? {}
77
- : T extends TypedArray ? Record<string, number>
78
- : T extends Array<infer U>
79
- ? Array<Jsonify<U extends NotJsonable ? null : U>> // It's an array: recursive call for its children
80
- : T extends object
81
- ? T extends {toJSON(): infer J}
82
- ? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
83
- ? J // Then T is Jsonable and its Jsonable value is J
84
- : never // Not Jsonable because its toJSON() method does not return JsonValue
85
- : {[P in keyof T as P extends symbol
86
- ? never
87
- : T[P] extends NotJsonable
88
- ? never
89
- : P]: Jsonify<Required<T>[P]>} // It's an object: recursive call for its children
90
- : never // Otherwise any other non-object is removed
70
+ ? T extends PositiveInfinity | NegativeInfinity ? null
71
+ : T extends JsonPrimitive ? T // Primitive is acceptable
72
+ : T extends object
73
+ // Any object with toJSON is special case
74
+ ? T extends {toJSON(): infer J} ? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
75
+ ? J // Then T is Jsonable and its Jsonable value is J
76
+ : never // Not Jsonable because its toJSON() method does not return JsonValue
77
+ // Instanced primitives are objects
78
+ : T extends Number ? number
79
+ : T extends String ? string
80
+ : T extends Boolean ? boolean
81
+ : T extends Map<any, any> | Set<any> ? {}
82
+ : T extends TypedArray ? Record<string, number>
83
+ : T extends any[]
84
+ ? {[I in keyof T]: T[I] extends NotJsonable ? null : Jsonify<T[I]>}
85
+ : {[P in keyof T as P extends symbol ? never
86
+ : T[P] extends NotJsonable ? never
87
+ : P
88
+ ]: Jsonify<Required<T>[P]>} // Recursive call for its children
89
+ : never // Otherwise any other non-object is removed
91
90
  : never; // Otherwise non-JSONable type union was found not empty
@@ -223,15 +223,17 @@ declare namespace PackageJson {
223
223
  string
224
224
  >;
225
225
 
226
+ type ExportConditions = {[condition in ExportCondition]: Exports};
227
+
226
228
  /**
227
229
  Entry points of a module, optionally with conditions and subpath exports.
228
230
  */
229
231
  export type Exports =
230
232
  | null
231
233
  | string
232
- | string[]
233
- | {[key in ExportCondition]: Exports}
234
- | {[key: string]: Exports}; // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
234
+ | Array<string | ExportConditions>
235
+ | ExportConditions
236
+ | {[path: string]: Exports}; // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
235
237
 
236
238
  /**
237
239
  Import map entries of a module, optionally with conditions.
@@ -0,0 +1,70 @@
1
+ import type {BuiltIns} from './internal';
2
+ import type {Merge} from './merge';
3
+
4
+ /**
5
+ @see PartialOnUndefinedDeep
6
+ */
7
+ export interface PartialOnUndefinedDeepOptions {
8
+ /**
9
+ Whether to affect the individual elements of arrays and tuples.
10
+
11
+ @default false
12
+ */
13
+ readonly recurseIntoArrays?: boolean;
14
+ }
15
+
16
+ /**
17
+ Create a deep version of another type where all keys accepting `undefined` type are set to optional.
18
+
19
+ This utility type is recursive, transforming at any level deep. By default, it does not affect arrays and tuples items unless you explicitly pass `{recurseIntoArrays: true}` as the second type argument.
20
+
21
+ Use-cases:
22
+ - Make all properties of a type that can be undefined optional to not have to specify keys with undefined value.
23
+
24
+ @example
25
+ ```
26
+ import type {PartialOnUndefinedDeep} from 'type-fest';
27
+
28
+ interface Settings {
29
+ optionA: string;
30
+ optionB: number | undefined;
31
+ subOption: {
32
+ subOptionA: boolean;
33
+ subOptionB: boolean | undefined;
34
+ }
35
+ };
36
+
37
+ const testSettings: PartialOnUndefinedDeep<Settings> = {
38
+ optionA: 'foo',
39
+ // 👉 optionB is now optional and can be omitted
40
+ subOption: {
41
+ subOptionA: true,
42
+ // 👉 subOptionB is now optional as well and can be omitted
43
+ },
44
+ };
45
+ ```
46
+
47
+ @category Object
48
+ */
49
+ export type PartialOnUndefinedDeep<T, Options extends PartialOnUndefinedDeepOptions = {}> = T extends Record<any, any> | undefined
50
+ ? {[KeyType in keyof T as undefined extends T[KeyType] ? KeyType : never]?: PartialOnUndefinedDeepValue<T[KeyType], Options>} extends infer U // Make a partial type with all value types accepting undefined (and set them optional)
51
+ ? Merge<{[KeyType in keyof T as KeyType extends keyof U ? never : KeyType]: PartialOnUndefinedDeepValue<T[KeyType], Options>}, U> // Join all remaining keys not treated in U
52
+ : never // Should not happen
53
+ : T;
54
+
55
+ /**
56
+ Utility type to get the value type by key and recursively call `PartialOnUndefinedDeep` to transform sub-objects.
57
+ */
58
+ type PartialOnUndefinedDeepValue<T, Options extends PartialOnUndefinedDeepOptions> = T extends BuiltIns | ((...arguments: any[]) => unknown)
59
+ ? T
60
+ : T extends ReadonlyArray<infer U> // Test if type is array or tuple
61
+ ? Options['recurseIntoArrays'] extends true // Check if option is activated
62
+ ? U[] extends T // Check if array not tuple
63
+ ? readonly U[] extends T
64
+ ? ReadonlyArray<PartialOnUndefinedDeep<U, Options>> // Readonly array treatment
65
+ : Array<PartialOnUndefinedDeep<U, Options>> // Mutable array treatment
66
+ : PartialOnUndefinedDeep<{[Key in keyof T]: PartialOnUndefinedDeep<T[Key], Options>}, Options> // Tuple treatment
67
+ : T
68
+ : T extends Record<any, any> | undefined
69
+ ? PartialOnUndefinedDeep<T, Options>
70
+ : unknown;
@@ -0,0 +1,35 @@
1
+ import type {Except} from './except';
2
+ import type {Simplify} from './simplify';
3
+
4
+ /**
5
+ Create a type that makes the given keys non-nullable. The remaining keys are kept as is.
6
+
7
+ Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are non-nullable.
8
+
9
+ @example
10
+ ```
11
+ import type {SetNonNullable} from 'type-fest';
12
+
13
+ type Foo = {
14
+ a: number;
15
+ b: string | undefined;
16
+ c?: boolean | null;
17
+ }
18
+
19
+ type SomeNonNullable = SetNonNullable<Foo, 'b' | 'c'>;
20
+ // type SomeNonNullable = {
21
+ // a: number;
22
+ // b: string; // Can no longer be undefined.
23
+ // c?: boolean; // Can no longer be null, but is still optional.
24
+ // }
25
+ ```
26
+
27
+ @category Object
28
+ */
29
+ export type SetNonNullable<BaseType, Keys extends keyof BaseType> =
30
+ Simplify<
31
+ // Pick just the keys that are readonly from the base type.
32
+ Except<BaseType, Keys> &
33
+ // Pick the keys that should be non-nullable from the base type and make them non-nullable.
34
+ {[Key in Keys]: NonNullable<BaseType[Key]>}
35
+ >;
@@ -0,0 +1,85 @@
1
+ import type {Except} from './except';
2
+ import type {RequiredKeysOf} from './required-keys-of';
3
+ import type {Simplify} from './simplify';
4
+
5
+ type SpreadObject<FirstType extends object, SecondType extends object> = {
6
+ [Key in keyof FirstType]: Key extends keyof SecondType
7
+ ? FirstType[Key] | Required<SecondType>[Key]
8
+ : FirstType[Key];
9
+ } & Pick<
10
+ SecondType,
11
+ RequiredKeysOf<SecondType> | Exclude<keyof SecondType, keyof FirstType>
12
+ >;
13
+
14
+ type TupleOrArray = readonly [...unknown[]];
15
+
16
+ type SpreadTupleOrArray<
17
+ FirstType extends TupleOrArray,
18
+ SecondType extends TupleOrArray,
19
+ > = Array<FirstType[number] | SecondType[number]>;
20
+
21
+ type Spreadable = object | TupleOrArray;
22
+
23
+ /**
24
+ Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.
25
+
26
+ @example
27
+ ```
28
+ import type {Spread} from 'type-fest';
29
+
30
+ type Foo = {
31
+ a: number;
32
+ b?: string;
33
+ };
34
+
35
+ type Bar = {
36
+ b?: number;
37
+ c: boolean;
38
+ };
39
+
40
+ const foo = {a: 1, b: '2'};
41
+ const bar = {c: false};
42
+ const fooBar = {...foo, ...bar};
43
+
44
+ type FooBar = Spread<Foo, Bar>;
45
+ // type FooBar = {
46
+ // a: number;
47
+ // b?: string | number | undefined;
48
+ // c: boolean;
49
+ // }
50
+
51
+ const baz = (argument: FooBar) => {
52
+ // Do something
53
+ }
54
+
55
+ baz(fooBar);
56
+ ```
57
+
58
+ @example
59
+ ```
60
+ import type {Spread} from 'type-fest';
61
+
62
+ const foo = [1, 2, 3];
63
+ const bar = ['4', '5', '6'];
64
+
65
+ const fooBar = [...foo, ...bar];
66
+ type FooBar = Spread<typeof foo, typeof bar>;
67
+ // FooBar = (string | number)[]
68
+
69
+ const baz = (argument: FooBar) => {
70
+ // Do something
71
+ };
72
+
73
+ baz(fooBar);
74
+ ```
75
+
76
+ @category Object
77
+ */
78
+ export type Spread<
79
+ FirstType extends Spreadable,
80
+ SecondType extends Spreadable,
81
+ > = FirstType extends TupleOrArray
82
+ ? SecondType extends TupleOrArray
83
+ ? SpreadTupleOrArray<FirstType, SecondType>
84
+ : Simplify<SpreadObject<FirstType, SecondType>>
85
+ : Simplify<SpreadObject<FirstType, SecondType>>;