type-fest 3.1.0 → 3.2.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
@@ -50,6 +50,7 @@ export type {SetReturnType} from './source/set-return-type';
50
50
  export type {Asyncify} from './source/asyncify';
51
51
  export type {Simplify} from './source/simplify';
52
52
  export type {Jsonify} from './source/jsonify';
53
+ export type {Jsonifiable} from './source/jsonifiable';
53
54
  export type {Schema} from './source/schema';
54
55
  export type {LiteralToPrimitive} from './source/literal-to-primitive';
55
56
  export type {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "type-fest",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "A collection of essential TypeScript types",
5
5
  "license": "(MIT OR CC0-1.0)",
6
6
  "repository": "sindresorhus/type-fest",
@@ -35,10 +35,10 @@
35
35
  ],
36
36
  "devDependencies": {
37
37
  "@sindresorhus/tsconfig": "~0.7.0",
38
- "expect-type": "^0.14.2",
38
+ "expect-type": "^0.15.0",
39
39
  "tsd": "^0.24.1",
40
- "typescript": "^4.8.3",
41
- "xo": "^0.52.2"
40
+ "typescript": "^4.8.4",
41
+ "xo": "^0.52.4"
42
42
  },
43
43
  "xo": {
44
44
  "rules": {
package/readme.md CHANGED
@@ -187,6 +187,7 @@ Click the type names for complete docs.
187
187
  ### JSON
188
188
 
189
189
  - [`Jsonify`](source/jsonify.d.ts) - Transform a type to one that is assignable to the `JsonValue` type.
190
+ - [`Jsonifiable`](source/jsonifiable.d.ts) - Matches a value that can be losslessly converted to JSON.
190
191
  - [`JsonPrimitive`](source/basic.d.ts) - Matches a JSON primitive.
191
192
  - [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
192
193
  - [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
@@ -213,7 +214,7 @@ Click the type names for complete docs.
213
214
  - [`MultidimensionalArray`](source/multidimensional-array.d.ts) - Create a type that represents a multidimensional array of the given type and dimensions.
214
215
  - [`MultidimensionalReadonlyArray`](source/multidimensional-readonly-array.d.ts) - Create a type that represents a multidimensional readonly array of the given type and dimensions.
215
216
  - [`ReadonlyTuple`](source/readonly-tuple.d.ts) - Create a type that represents a read-only tuple of the given type and length.
216
- - [`TupleToUnion`](source/tuple-to-union.d.ts) - Convert a tuple into a union type of its elements.
217
+ - [`TupleToUnion`](source/tuple-to-union.d.ts) - Convert a tuple/array into a union type of its elements.
217
218
 
218
219
  ### Numeric
219
220
 
@@ -1,39 +1,42 @@
1
- import type {WordSeparators} from '../source/internal';
2
- import type {Split} from './split';
1
+ import type {SplitWords} from './split-words';
3
2
 
4
3
  /**
5
- Step by step takes the first item in an array literal, formats it and adds it to a string literal, and then recursively appends the remainder.
4
+ CamelCase options.
6
5
 
7
- Only to be used by `CamelCaseStringArray<>`.
8
-
9
- @see CamelCaseStringArray
6
+ @see {@link CamelCase}
10
7
  */
11
- type InnerCamelCaseStringArray<Parts extends readonly any[], PreviousPart> =
12
- Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
13
- ? FirstPart extends undefined
14
- ? ''
15
- : FirstPart extends ''
16
- ? InnerCamelCaseStringArray<RemainingParts, PreviousPart>
17
- : `${PreviousPart extends '' ? FirstPart : Capitalize<FirstPart>}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`
18
- : '';
19
-
20
- /**
21
- Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal.
8
+ export type CamelCaseOptions = {
9
+ /**
10
+ Whether to preserved consecutive uppercase letter.
22
11
 
23
- It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code.
12
+ @default true
13
+ */
14
+ preserveConsecutiveUppercase?: boolean;
15
+ };
24
16
 
25
- @see Split
17
+ /**
18
+ Convert an array of words to camel-case.
26
19
  */
27
- type CamelCaseStringArray<Parts extends readonly string[]> =
28
- Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
29
- ? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray<RemainingParts, FirstPart>}`>
30
- : never;
20
+ type CamelCaseFromArray<
21
+ Words extends string[],
22
+ Options extends CamelCaseOptions,
23
+ OutputString extends string = '',
24
+ > = Words extends [
25
+ infer FirstWord extends string,
26
+ ...infer RemainingWords extends string[],
27
+ ]
28
+ ? Options['preserveConsecutiveUppercase'] extends true
29
+ ? `${Capitalize<FirstWord>}${CamelCaseFromArray<RemainingWords, Options>}`
30
+ : `${Capitalize<Lowercase<FirstWord>>}${CamelCaseFromArray<RemainingWords, Options>}`
31
+ : OutputString;
31
32
 
32
33
  /**
33
34
  Convert a string literal to camel-case.
34
35
 
35
36
  This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result.
36
37
 
38
+ By default, consecutive uppercase letter are preserved. See {@link CamelCaseOptions.preserveConsecutiveUppercase preserveConsecutiveUppercase} option to change this behaviour.
39
+
37
40
  @example
38
41
  ```
39
42
  import type {CamelCase} from 'type-fest';
@@ -70,4 +73,6 @@ const dbResult: CamelCasedProperties<RawOptions> = {
70
73
  @category Change case
71
74
  @category Template literal
72
75
  */
73
- export type CamelCase<K> = K extends string ? CamelCaseStringArray<Split<K extends Uppercase<K> ? Lowercase<K> : K, WordSeparators>> : K;
76
+ export type CamelCase<Type, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Type extends string
77
+ ? Uncapitalize<CamelCaseFromArray<SplitWords<Type extends Uppercase<Type> ? Lowercase<Type> : Type>, Options>>
78
+ : Type;
@@ -1,4 +1,4 @@
1
- import type {CamelCase} from './camel-case';
1
+ import type {CamelCase, CamelCaseOptions} from './camel-case';
2
2
 
3
3
  /**
4
4
  Convert object properties to camel case recursively.
@@ -44,11 +44,11 @@ const result: CamelCasedPropertiesDeep<UserWithFriends> = {
44
44
  @category Template literal
45
45
  @category Object
46
46
  */
47
- export type CamelCasedPropertiesDeep<Value> = Value extends Function
47
+ export type CamelCasedPropertiesDeep<Value, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Value extends Function
48
48
  ? Value
49
49
  : Value extends Array<infer U>
50
- ? Array<CamelCasedPropertiesDeep<U>>
50
+ ? Array<CamelCasedPropertiesDeep<U, Options>>
51
51
  : Value extends Set<infer U>
52
- ? Set<CamelCasedPropertiesDeep<U>> : {
53
- [K in keyof Value as CamelCase<K>]: CamelCasedPropertiesDeep<Value[K]>;
52
+ ? Set<CamelCasedPropertiesDeep<U, Options>> : {
53
+ [K in keyof Value as CamelCase<K, Options>]: CamelCasedPropertiesDeep<Value[K], Options>;
54
54
  };
@@ -1,4 +1,4 @@
1
- import type {CamelCase} from './camel-case';
1
+ import type {CamelCase, CamelCaseOptions} from './camel-case';
2
2
 
3
3
  /**
4
4
  Convert object properties to camel case but not recursively.
@@ -27,10 +27,10 @@ const result: CamelCasedProperties<User> = {
27
27
  @category Template literal
28
28
  @category Object
29
29
  */
30
- export type CamelCasedProperties<Value> = Value extends Function
30
+ export type CamelCasedProperties<Value, Options extends CamelCaseOptions = {preserveConsecutiveUppercase: true}> = Value extends Function
31
31
  ? Value
32
32
  : Value extends Array<infer U>
33
33
  ? Value
34
34
  : {
35
- [K in keyof Value as CamelCase<K>]: Value[K];
35
+ [K in keyof Value as CamelCase<K, Options>]: Value[K];
36
36
  };
@@ -1,9 +1,9 @@
1
1
  import type {UpperCaseCharacters, WordSeparators} from '../source/internal';
2
2
 
3
- // Transforms a string that is fully uppercase into a fully lowercase version. Needed to add support for SCREMAING_SNAKE_CASE, see https://github.com/sindresorhus/type-fest/issues/385
3
+ // Transforms a string that is fully uppercase into a fully lowercase version. Needed to add support for SCREAMING_SNAKE_CASE, see https://github.com/sindresorhus/type-fest/issues/385
4
4
  type UpperCaseToLowerCase<T extends string> = T extends Uppercase<T> ? Lowercase<T> : T;
5
5
 
6
- // This implemntation does not supports SCREMAING_SNAKE_CASE, it used internaly by `SplitIncludingDelimiters`.
6
+ // This implementation does not support SCREAMING_SNAKE_CASE, it is used internally by `SplitIncludingDelimiters`.
7
7
  type SplitIncludingDelimiters_<Source extends string, Delimiter extends string> =
8
8
  Source extends '' ? [] :
9
9
  Source extends `${infer FirstPart}${Delimiter}${infer SecondPart}` ?
@@ -19,7 +19,7 @@ Enforce optional keys (by adding the `?` operator) for keys that have a union wi
19
19
 
20
20
  @example
21
21
  ```
22
- import type {Merge} from 'type-fest';
22
+ import type {EnforceOptional} from 'type-fest';
23
23
 
24
24
  type Foo = {
25
25
  a: string;
@@ -6,7 +6,7 @@ type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
6
6
  /**
7
7
  Create a type that represents an array of the given type and length. The array's length and the `Array` prototype methods that manipulate its length are excluded in the resulting type.
8
8
 
9
- Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similiar type built into TypeScript.
9
+ Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similar type built into TypeScript.
10
10
 
11
11
  Use-cases:
12
12
  - Declaring fixed-length tuples or arrays with a large number of items.
@@ -93,3 +93,18 @@ export type FirstArrayElement<TArray extends UnknownArrayOrTuple> = TArray exten
93
93
  Extracts the type of an array or tuple minus the first element.
94
94
  */
95
95
  export type ArrayTail<TArray extends UnknownArrayOrTuple> = TArray extends readonly [unknown, ...infer TTail] ? TTail : [];
96
+
97
+ /**
98
+ Returns a boolean for whether the string is lowercased.
99
+ */
100
+ export type IsLowerCase<T extends string> = T extends Lowercase<T> ? true : false;
101
+
102
+ /**
103
+ Returns a boolean for whether the string is uppercased.
104
+ */
105
+ export type IsUpperCase<T extends string> = T extends Uppercase<T> ? true : false;
106
+
107
+ /**
108
+ Returns a boolean for whether the string is numeric.
109
+ */
110
+ export type IsNumeric<T extends string> = T extends `${number}` ? true : false;
@@ -0,0 +1,37 @@
1
+ import type {JsonPrimitive, JsonValue} from './basic';
2
+
3
+ type JsonifiableObject = {[Key in string]?: Jsonifiable} | {toJSON: () => Jsonifiable};
4
+ type JsonifiableArray = readonly Jsonifiable[];
5
+
6
+ /**
7
+ Matches a value that can be losslessly converted to JSON.
8
+
9
+ Can be used to type values that you expect to pass to `JSON.stringify`.
10
+
11
+ `undefined` is allowed in object fields (for example, `{a?: number}`) as a special case even though `JSON.stringify({a: undefined})` is `{}` because it makes this class more widely useful and checking for undefined-but-present values is likely an anti-pattern.
12
+
13
+ @example
14
+ ```
15
+ import type {Jsonifiable} from 'type-fest';
16
+
17
+ // @ts-expect-error
18
+ const error: Jsonifiable = {
19
+ map: new Map([['a', 1]]),
20
+ };
21
+
22
+ JSON.stringify(error);
23
+ //=> {"map": {}}
24
+
25
+ const good: Jsonifiable = {
26
+ number: 3,
27
+ date: new Date(),
28
+ missing: undefined,
29
+ }
30
+
31
+ JSON.stringify(good);
32
+ //=> {"number": 3, "date": "2022-10-17T22:22:35.920Z"}
33
+ ```
34
+
35
+ @category JSON
36
+ */
37
+ export type Jsonifiable = JsonPrimitive | JsonifiableObject | JsonifiableArray;
@@ -1,4 +1,5 @@
1
1
  import type {JsonPrimitive, JsonValue} from './basic';
2
+ import type {EmptyObject} from './empty-object';
2
3
  import type {Merge} from './merge';
3
4
  import type {NegativeInfinity, PositiveInfinity} from './numeric';
4
5
  import type {TypedArray} from './typed-array';
@@ -95,12 +96,12 @@ export type Jsonify<T> =
95
96
  // Any object with toJSON is special case
96
97
  ? T extends {toJSON(): infer J} ? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
97
98
  ? J // Then T is Jsonable and its Jsonable value is J
98
- : never // Not Jsonable because its toJSON() method does not return JsonValue
99
+ : Jsonify<J> // Maybe if we look a level deeper we'll find a JsonValue
99
100
  // Instanced primitives are objects
100
101
  : T extends Number ? number
101
102
  : T extends String ? string
102
103
  : T extends Boolean ? boolean
103
- : T extends Map<any, any> | Set<any> ? {}
104
+ : T extends Map<any, any> | Set<any> ? EmptyObject
104
105
  : T extends TypedArray ? Record<string, number>
105
106
  : T extends any[]
106
107
  ? {[I in keyof T]: T[I] extends NotJsonable ? null : Jsonify<T[I]>}
@@ -13,7 +13,7 @@ import type {
13
13
  } from './internal';
14
14
 
15
15
  /**
16
- Deeply smplifies an object excluding iterables and functions. Used internally to improve the UX and accept both interfaces and type aliases as inputs.
16
+ Deeply simplifies an object excluding iterables and functions. Used internally to improve the UX and accept both interfaces and type aliases as inputs.
17
17
  */
18
18
  type SimplifyDeep<Type> = ConditionalSimplifyDeep<Type, Function | Iterable<unknown>, object>;
19
19
 
@@ -200,7 +200,7 @@ Merge mode for array/tuple elements.
200
200
  type ArrayMergeMode = 'spread' | 'replace';
201
201
 
202
202
  /**
203
- Test if it sould spread top-level arrays.
203
+ Test if it should spread top-level arrays.
204
204
  */
205
205
  type ShouldSpread<Options extends MergeDeepInternalOptions> = Options['spreadTopLevelArrays'] extends false
206
206
  ? Options['arrayMergeMode'] extends 'spread' ? true : false
@@ -8,7 +8,7 @@ declare global {
8
8
  /**
9
9
  @remarks
10
10
  The TC39 observable proposal defines a `closed` property, but some implementations (such as xstream) do not as of 10/08/2021.
11
- As well, some guideance on making an `Observable` do not include `closed` propery.
11
+ As well, some guidance on making an `Observable` to not include `closed` property.
12
12
  @see https://github.com/tc39/proposal-observable/blob/master/src/Observable.js#L129-L130
13
13
  @see https://github.com/staltz/xstream/blob/6c22580c1d84d69773ee4b0905df44ad464955b3/src/index.ts#L79-L85
14
14
  @see https://github.com/benlesh/symbol-observable#making-an-object-observable
@@ -240,7 +240,7 @@ declare namespace PackageJson {
240
240
  Import map entries of a module, optionally with conditions.
241
241
  */
242
242
  export type Imports = { // eslint-disable-line @typescript-eslint/consistent-indexed-object-style
243
- [key: string]: string | {[key in ExportCondition]: Exports};
243
+ [key: `#${string}`]: string | {[key in ExportCondition]: Exports};
244
244
  };
245
245
 
246
246
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
@@ -29,7 +29,6 @@ const userMaskSettings: UserMask = {
29
29
  firstname: 'show',
30
30
  lastname: 'mask',
31
31
  },
32
- phoneNumbers: 'mask',
33
32
  created: 'show',
34
33
  active: 'show',
35
34
  passwordHash: 'hide',
@@ -0,0 +1,57 @@
1
+ import type {IsLowerCase, IsNumeric, IsUpperCase, WordSeparators} from './internal';
2
+
3
+ type SkipEmptyWord<Word extends string> = Word extends '' ? [] : [Word];
4
+
5
+ type RemoveLastCharacter<Sentence extends string, Character extends string> = Sentence extends `${infer LeftSide}${Character}`
6
+ ? SkipEmptyWord<LeftSide>
7
+ : never;
8
+
9
+ /**
10
+ Split a string (almost) like Lodash's `_.words()` function.
11
+
12
+ - Split on each word that begins with a capital letter.
13
+ - Split on each {@link WordSeparators}.
14
+ - Split on numeric sequence.
15
+
16
+ @example
17
+ ```
18
+ type Words0 = SplitWords<'helloWorld'>; // ['hello', 'World']
19
+ type Words1 = SplitWords<'helloWORLD'>; // ['hello', 'WORLD']
20
+ type Words2 = SplitWords<'hello-world'>; // ['hello', 'world']
21
+ type Words3 = SplitWords<'--hello the_world'>; // ['hello', 'the', 'world']
22
+ type Words4 = SplitWords<'lifeIs42'>; // ['life', 'Is', '42']
23
+ ```
24
+
25
+ @internal
26
+ @category Change case
27
+ @category Template literal
28
+ */
29
+ export type SplitWords<
30
+ Sentence extends string,
31
+ LastCharacter extends string = '',
32
+ CurrentWord extends string = '',
33
+ > = Sentence extends `${infer FirstCharacter}${infer RemainingCharacters}`
34
+ ? FirstCharacter extends WordSeparators
35
+ // Skip word separator
36
+ ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, LastCharacter>]
37
+ : LastCharacter extends ''
38
+ // Fist char of word
39
+ ? SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>
40
+ // Case change: non-numeric to numeric, push word
41
+ : [false, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
42
+ ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
43
+ // Case change: numeric to non-numeric, push word
44
+ : [true, false] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
45
+ ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
46
+ // No case change: concat word
47
+ : [true, true] extends [IsNumeric<LastCharacter>, IsNumeric<FirstCharacter>]
48
+ ? SplitWords<RemainingCharacters, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
49
+ // Case change: lower to upper, push word
50
+ : [true, true] extends [IsLowerCase<LastCharacter>, IsUpperCase<FirstCharacter>]
51
+ ? [...SkipEmptyWord<CurrentWord>, ...SplitWords<RemainingCharacters, FirstCharacter, FirstCharacter>]
52
+ // Case change: upper to lower, brings back the last character, push word
53
+ : [true, true] extends [IsUpperCase<LastCharacter>, IsLowerCase<FirstCharacter>]
54
+ ? [...RemoveLastCharacter<CurrentWord, LastCharacter>, ...SplitWords<RemainingCharacters, FirstCharacter, `${LastCharacter}${FirstCharacter}`>]
55
+ // No case change: concat word
56
+ : SplitWords<RemainingCharacters, FirstCharacter, `${CurrentWord}${FirstCharacter}`>
57
+ : [...SkipEmptyWord<CurrentWord>];
@@ -1,5 +1,5 @@
1
1
  /**
2
- Convert a tuple into a union type of its elements.
2
+ Convert a tuple/array into a union type of its elements.
3
3
 
4
4
  This can be useful when you have a fixed set of allowed values and want a type defining only the allowed values, but do not want to repeat yourself.
5
5
 
@@ -48,4 +48,4 @@ type NumberBool = typeof numberBool[number];
48
48
 
49
49
  @category Array
50
50
  */
51
- export type TupleToUnion<ArrayType> = ArrayType extends readonly [infer Head, ...(infer Rest)] ? Head | TupleToUnion<Rest> : never;
51
+ export type TupleToUnion<ArrayType> = ArrayType extends readonly unknown[] ? ArrayType[number] : never;