@ashetm/types 1.3.0 → 1.3.2

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/README.md CHANGED
@@ -20,6 +20,7 @@ It is **types only**: it adds nothing to your bundle. It works with any project
20
20
  | 4.5+ | 13.1+ | all |
21
21
 
22
22
  Your TypeScript version picks the right types by itself (`typesVersions`): nothing to configure.
23
+ It works from ESM and CommonJS projects (`module: node16` / `nodenext` included), and from bundlers.
23
24
 
24
25
  ## Install
25
26
 
@@ -221,6 +222,8 @@ type D = SnakeCase<'user-name id'>; // 'user_name_id'
221
222
 
222
223
  `Brand<T, Name>` tags `T` with a name, so two types with the same shape can't be mixed up. A branded value is still a `T`; a plain `T` must be cast to get the brand.
223
224
 
225
+ The brand is a type-only `__brand` key (nothing at runtime), so the same `Brand` from an ESM and a CommonJS project match. A `Brand` from 1.3.0 or 1.3.1 does not match one from 1.3.2+ if both versions are installed.
226
+
224
227
  ```ts
225
228
  type UserId = Brand<string, 'UserId'>;
226
229
  type OrderId = Brand<string, 'OrderId'>;
@@ -243,7 +246,8 @@ npm run test:compat
243
246
  ```
244
247
 
245
248
  - `npm test` type-checks the type tests (`src/*.spec-d.ts`): what must compile, and `// @ts-expect-error` for what must not. Nothing runs.
246
- - `npm run test:compat` builds, then checks the package like a real install (`compat/`, linked as `@ashetm/types`) with TypeScript 3.7, 4.0, 4.1, 4.4, 5.0, 6 and the latest (downloaded with `npx`).
249
+ - `npm run test:compat` builds, then checks the package like a real install (`compat/`, linked as `@ashetm/types`) with TypeScript 3.7, 4.0, 4.1, 4.4, 5.0, 6 and the latest (downloaded with `npx`), and a CommonJS and an ESM consumer (`module: node16`) with TypeScript 4.7, 5.0, 5.7 and the latest.
250
+ - `npm run build` also writes the CommonJS declarations (`dist/*.d.cts`, `scripts/build-cjs.mjs`) for the `require` condition of `exports`.
247
251
  - `src/legacy.ts` holds the TypeScript 3.7 types: TypeScript < 4.1 reads only this file. Types that need TypeScript 4.1+ are exported from `src/index.ts` only.
248
252
 
249
253
  ## License
@@ -0,0 +1,22 @@
1
+ /**
2
+ * An array with at least one item.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * const ids: NonEmptyArray<number> = [1, 2, 3];
7
+ * const first: number = ids[0]; // `number`, not `number | undefined` with `noUncheckedIndexedAccess`
8
+ *
9
+ * const none: NonEmptyArray<number> = []; // error
10
+ * ```
11
+ */
12
+ export type NonEmptyArray<T> = [T, ...T[]];
13
+ /**
14
+ * The item type of an array or a tuple (readonly too).
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * type Id = ArrayItem<number[]>; // number
19
+ * type Role = ArrayItem<readonly ['admin', 'user']>; // 'admin' | 'user'
20
+ * ```
21
+ */
22
+ export type ArrayItem<T extends ReadonlyArray<unknown>> = T[number];
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `T` tagged with a `Name`, so two types with the same shape can't be mixed up.
3
+ * A branded value is still a `T`; a plain `T` must be cast to get the brand.
4
+ *
5
+ * The brand is a type-only `__brand` key: it does not exist at runtime. A string key (not a `unique symbol`)
6
+ * keeps the ESM and CommonJS copies of this type the same.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * type UserId = Brand<string, 'UserId'>;
11
+ * type OrderId = Brand<string, 'OrderId'>;
12
+ *
13
+ * const userId = 'u-1' as UserId;
14
+ * const text: string = userId; // allowed
15
+ * const orderId: OrderId = userId; // error
16
+ * const other: UserId = 'u-2'; // error
17
+ * ```
18
+ */
19
+ export type Brand<T, Name extends string> = T & {
20
+ readonly __brand: Name;
21
+ };
package/dist/brand.d.ts CHANGED
@@ -1,8 +1,10 @@
1
- declare const brand: unique symbol;
2
1
  /**
3
2
  * `T` tagged with a `Name`, so two types with the same shape can't be mixed up.
4
3
  * A branded value is still a `T`; a plain `T` must be cast to get the brand.
5
4
  *
5
+ * The brand is a type-only `__brand` key: it does not exist at runtime. A string key (not a `unique symbol`)
6
+ * keeps the ESM and CommonJS copies of this type the same.
7
+ *
6
8
  * @example
7
9
  * ```ts
8
10
  * type UserId = Brand<string, 'UserId'>;
@@ -15,6 +17,5 @@ declare const brand: unique symbol;
15
17
  * ```
16
18
  */
17
19
  export type Brand<T, Name extends string> = T & {
18
- readonly [brand]: Name;
20
+ readonly __brand: Name;
19
21
  };
20
- export {};
@@ -0,0 +1,89 @@
1
+ type Builtin = string | number | boolean | bigint | symbol | null | undefined | Function | Date | RegExp | Error | Promise<unknown> | WeakMap<object, unknown> | WeakSet<object>;
2
+ /**
3
+ * `T` with every property optional, at every level.
4
+ *
5
+ * - Arrays and tuples: items are deep partial, tuples keep their length.
6
+ * - `Map` and `Set` (readonly too): values are deep partial, `Map` keys are kept.
7
+ * - Primitives, functions, `Date`, `RegExp`, `Error`, `Promise`, `WeakMap` and `WeakSet` are kept as they are.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * interface Settings {
12
+ * theme: { color: string; dark: boolean };
13
+ * tags: string[];
14
+ * }
15
+ *
16
+ * const patch: DeepPartial<Settings> = { theme: { dark: true } };
17
+ * ```
18
+ */
19
+ export type DeepPartial<T> = T extends Map<infer K, infer V> ? Map<K, DeepPartial<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<K, DeepPartial<V>> : T extends Set<infer U> ? Set<DeepPartial<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<DeepPartial<U>> : T extends Builtin ? T : T extends ReadonlyArray<unknown> ? {
20
+ [K in keyof T]: DeepPartial<T[K]>;
21
+ } : {
22
+ [K in keyof T]?: DeepPartial<T[K]>;
23
+ };
24
+ /**
25
+ * `T` with every property `readonly`, at every level.
26
+ *
27
+ * - Arrays and tuples become readonly arrays and tuples, with deep readonly items.
28
+ * - `Map` and `Set` become `ReadonlyMap` and `ReadonlySet`, with deep readonly values (`Map` keys are kept).
29
+ * - Primitives, functions, `Date`, `RegExp`, `Error`, `Promise`, `WeakMap` and `WeakSet` are kept as they are.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * interface Settings {
34
+ * theme: { color: string };
35
+ * tags: string[];
36
+ * }
37
+ *
38
+ * const settings: DeepReadonly<Settings> = { theme: { color: 'red' }, tags: ['a'] };
39
+ * settings.theme.color = 'blue'; // error
40
+ * settings.tags.push('b'); // error
41
+ * ```
42
+ */
43
+ export type DeepReadonly<T> = T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<K, DeepReadonly<V>> : T extends ReadonlySet<infer U> ? ReadonlySet<DeepReadonly<U>> : T extends Builtin ? T : {
44
+ readonly [K in keyof T]: DeepReadonly<T[K]>;
45
+ };
46
+ /**
47
+ * `T` with every property required, at every level: `?` is removed, with the `undefined` that came
48
+ * with it (an explicit `| undefined` is kept).
49
+ *
50
+ * - Arrays: items are deep required. Tuples: optional items become required.
51
+ * - `Map` and `Set` (readonly too): values are deep required, `Map` keys are kept.
52
+ * - Primitives, functions, `Date`, `RegExp`, `Error`, `Promise`, `WeakMap` and `WeakSet` are kept as they are.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * interface Options {
57
+ * retry?: { count?: number; delay?: number };
58
+ * }
59
+ *
60
+ * const defaults: DeepRequired<Options> = { retry: { count: 3, delay: 100 } };
61
+ * ```
62
+ */
63
+ export type DeepRequired<T> = T extends Map<infer K, infer V> ? Map<K, DeepRequired<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<K, DeepRequired<V>> : T extends Set<infer U> ? Set<DeepRequired<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<DeepRequired<U>> : T extends Builtin ? T : T extends ReadonlyArray<unknown> ? number extends T['length'] ? {
64
+ [K in keyof T]: DeepRequired<T[K]>;
65
+ } : {
66
+ [K in keyof T]-?: DeepRequired<T[K]>;
67
+ } : {
68
+ [K in keyof T]-?: DeepRequired<T[K]>;
69
+ };
70
+ /**
71
+ * `T` without `readonly`, at every level.
72
+ *
73
+ * - Readonly arrays and tuples become mutable, with deep mutable items.
74
+ * - `ReadonlyMap` and `ReadonlySet` become `Map` and `Set`, with deep mutable values (`Map` keys are kept).
75
+ * - Primitives, functions, `Date`, `RegExp`, `Error`, `Promise`, `WeakMap` and `WeakSet` are kept as they are.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const defaults = { theme: { color: 'red' }, tags: ['a'] } as const;
80
+ *
81
+ * const settings: DeepMutable<typeof defaults> = { theme: { color: 'red' }, tags: ['a'] };
82
+ * settings.theme.color = 'red'; // allowed
83
+ * settings.tags.push('a'); // allowed
84
+ * ```
85
+ */
86
+ export type DeepMutable<T> = T extends ReadonlyMap<infer K, infer V> ? Map<K, DeepMutable<V>> : T extends ReadonlySet<infer U> ? Set<DeepMutable<U>> : T extends Builtin ? T : {
87
+ -readonly [K in keyof T]: DeepMutable<T[K]>;
88
+ };
89
+ export {};
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+ module.exports = {};
@@ -0,0 +1,4 @@
1
+ export * from './legacy.cjs';
2
+ export * from './path.cjs';
3
+ export * from './string.cjs';
4
+ export * from './tuple.cjs';
@@ -0,0 +1,23 @@
1
+ /** A JSON primitive: `string`, `number`, `boolean` or `null`. */
2
+ export type JsonPrimitive = string | number | boolean | null;
3
+ /**
4
+ * Any JSON value: what `JSON.parse` can return.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * const payload: JsonValue = { id: 1, tags: ['a'], meta: null };
9
+ * const invalid: JsonValue = { at: new Date() }; // error
10
+ * ```
11
+ */
12
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
13
+ /**
14
+ * A JSON object.
15
+ *
16
+ * An `interface` has no index signature, so a value typed with one is not assignable to `JsonObject`:
17
+ * use a `type` instead. Optional properties are not allowed (`undefined` is not JSON).
18
+ */
19
+ export type JsonObject = {
20
+ [key: string]: JsonValue;
21
+ };
22
+ /** A JSON array. */
23
+ export type JsonArray = JsonValue[];
@@ -0,0 +1,7 @@
1
+ export * from './array.cjs';
2
+ export * from './brand.cjs';
3
+ export * from './deep.cjs';
4
+ export * from './json.cjs';
5
+ export * from './nullable.cjs';
6
+ export * from './object.cjs';
7
+ export * from './union.cjs';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `T` or `null`.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * let user: Nullable<User> = null;
7
+ * ```
8
+ */
9
+ export type Nullable<T> = T | null;
10
+ /**
11
+ * `T`, `null` or `undefined`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * function greet(name: Maybe<string>): string {
16
+ * return `Hello ${name ?? 'stranger'}`;
17
+ * }
18
+ * ```
19
+ */
20
+ export type Maybe<T> = T | null | undefined;
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The union of the value types of an object.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * const Status = { Active: 'active', Archived: 'archived' } as const;
7
+ *
8
+ * type Status = ValueOf<typeof Status>; // 'active' | 'archived'
9
+ * ```
10
+ */
11
+ export type ValueOf<T> = T[keyof T];
12
+ /**
13
+ * The keys of `T` whose value is assignable to `V`. `undefined` is ignored, so an optional key
14
+ * like `nickname?: string` counts for `V = string`.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * interface User {
19
+ * id: number;
20
+ * name: string;
21
+ * nickname?: string;
22
+ * }
23
+ *
24
+ * type TextKeys = KeysOfType<User, string>; // 'name' | 'nickname'
25
+ * ```
26
+ */
27
+ export type KeysOfType<T, V> = {
28
+ [K in keyof T]-?: Exclude<T[K], undefined> extends V ? K : never;
29
+ }[keyof T];
30
+ /**
31
+ * `T` without `readonly` on its properties (one level, arrays and tuples too).
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * interface Point {
36
+ * readonly x: number;
37
+ * readonly y: number;
38
+ * }
39
+ *
40
+ * const point: Mutable<Point> = { x: 0, y: 0 };
41
+ * point.x = 1; // allowed
42
+ * ```
43
+ */
44
+ export type Mutable<T> = {
45
+ -readonly [K in keyof T]: T[K];
46
+ };
47
+ /**
48
+ * `T` with its intersections flattened into one object type, so hovers are readable.
49
+ * `readonly` and `?` are kept.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * type User = Prettify<{ id: number } & { name?: string }>; // { id: number; name?: string }
54
+ * ```
55
+ */
56
+ export type Prettify<T> = {
57
+ [K in keyof T]: T[K];
58
+ };
59
+ /**
60
+ * `T` with only the keys `K` optional.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * interface User {
65
+ * id: number;
66
+ * name: string;
67
+ * email: string;
68
+ * }
69
+ *
70
+ * type NewUser = PartialBy<User, 'id'>; // { name: string; email: string; id?: number }
71
+ * ```
72
+ */
73
+ export type PartialBy<T, K extends keyof T> = Prettify<Omit<T, K> & Partial<Pick<T, K>>>;
74
+ /**
75
+ * `T` with only the keys `K` required.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * interface Options {
80
+ * url?: string;
81
+ * timeout?: number;
82
+ * }
83
+ *
84
+ * type UrlOptions = RequiredBy<Options, 'url'>; // { timeout?: number; url: string }
85
+ * ```
86
+ */
87
+ export type RequiredBy<T, K extends keyof T> = Prettify<Omit<T, K> & Required<Pick<T, K>>>;
88
+ /**
89
+ * `T` where at least one of the keys `K` (all keys by default) must be set.
90
+ * The other keys of `K` stay optional; keys outside `K` are kept as they are.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * interface Contact {
95
+ * name: string;
96
+ * email?: string;
97
+ * phone?: string;
98
+ * }
99
+ *
100
+ * type ReachableContact = RequireAtLeastOne<Contact, 'email' | 'phone'>;
101
+ *
102
+ * const a: ReachableContact = { name: 'A', email: 'a@b.c' };
103
+ * const b: ReachableContact = { name: 'B', email: 'b@c.d', phone: '01' };
104
+ * const c: ReachableContact = { name: 'C' }; // error
105
+ * ```
106
+ */
107
+ export type RequireAtLeastOne<T, K extends keyof T = keyof T> = {
108
+ [P in K]-?: Prettify<Omit<T, K> & Required<Pick<T, P>> & Partial<Pick<T, Exclude<K, P>>>>;
109
+ }[K];
110
+ /**
111
+ * `T` where exactly one of the keys `K` (all keys by default) must be set; the other keys of `K`
112
+ * are not allowed. Keys outside `K` are kept as they are.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * interface Payment {
117
+ * amount: number;
118
+ * card?: string;
119
+ * iban?: string;
120
+ * }
121
+ *
122
+ * type SinglePayment = RequireExactlyOne<Payment, 'card' | 'iban'>;
123
+ *
124
+ * const a: SinglePayment = { amount: 1, card: '4242' };
125
+ * const b: SinglePayment = { amount: 1, card: '4242', iban: 'FR76' }; // error
126
+ * const c: SinglePayment = { amount: 1 }; // error
127
+ * ```
128
+ */
129
+ export type RequireExactlyOne<T, K extends keyof T = keyof T> = {
130
+ [P in K]-?: Prettify<Omit<T, K> & Required<Pick<T, P>> & {
131
+ [Q in Exclude<K, P>]?: never;
132
+ }>;
133
+ }[K];
134
+ /**
135
+ * A union with one object type per key of `T`. `readonly` and `?` are kept.
136
+ *
137
+ * TypeScript can't split an intersection back into its members, so
138
+ * `SplitKeys<A & B>` gives `A | B` only when `A` and `B` have one key each.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * type Change = SplitKeys<{ name: string; age?: number }>; // { name: string } | { age?: number }
143
+ * ```
144
+ */
145
+ export type SplitKeys<T> = {
146
+ [K in keyof T]-?: Prettify<Pick<T, K>>;
147
+ }[keyof T];
148
+ /**
149
+ * `A` with the properties of `B` on top: `B` wins on shared keys.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * type Row = Merge<{ id: number; name: string }, { id: string }>; // { name: string; id: string }
154
+ * ```
155
+ */
156
+ export type Merge<A, B> = Prettify<Omit<A, keyof B> & B>;
157
+ /**
158
+ * `Omit` that only accepts keys of `T`, so a typo or a renamed key is an error.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * interface User {
163
+ * id: number;
164
+ * name: string;
165
+ * }
166
+ *
167
+ * type Draft = StrictOmit<User, 'id'>; // { name: string }
168
+ * type Typo = StrictOmit<User, 'idd'>; // error
169
+ * ```
170
+ */
171
+ export type StrictOmit<T, K extends keyof T> = Omit<T, K>;
172
+ /**
173
+ * The keys of `T` marked `?`.
174
+ *
175
+ * @example
176
+ * ```ts
177
+ * type Keys = OptionalKeys<{ id: number; name?: string }>; // 'name'
178
+ * ```
179
+ */
180
+ export type OptionalKeys<T> = {
181
+ [K in keyof T]-?: Record<never, never> extends Pick<T, K> ? K : never;
182
+ }[keyof T];
183
+ /**
184
+ * The keys of `T` not marked `?` (a value that can be `undefined` is still required).
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * type Keys = RequiredKeys<{ id: number; name?: string }>; // 'id'
189
+ * ```
190
+ */
191
+ export type RequiredKeys<T> = {
192
+ [K in keyof T]-?: Record<never, never> extends Pick<T, K> ? never : K;
193
+ }[keyof T];
194
+ /**
195
+ * The `[key, value]` pairs of the object `T`, to type `Object.entries`. String keys only,
196
+ * like `Object.entries`.
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * interface User {
201
+ * id: number;
202
+ * name: string;
203
+ * }
204
+ *
205
+ * declare const user: User;
206
+ * const entries = Object.entries(user) as Entries<User>; // (['id', number] | ['name', string])[]
207
+ * ```
208
+ */
209
+ export type Entries<T> = Array<{
210
+ [K in keyof T]-?: K extends string ? [K, T[K]] : never;
211
+ }[keyof T]>;
@@ -0,0 +1,49 @@
1
+ type Leaf = string | number | boolean | bigint | symbol | null | undefined | Function | Date | RegExp | Error | Promise<unknown> | WeakMap<object, unknown> | WeakSet<object> | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>;
2
+ type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7];
3
+ type PathsAt<T, D extends number> = [D] extends [never] ? never : T extends Leaf ? never : T extends ReadonlyArray<infer U> ? `${number}` | `${number}.${PathsAt<NonNullable<U>, Depth[D]>}` : {
4
+ [K in keyof T & string]-?: K | `${K}.${PathsAt<NonNullable<T[K]>, Depth[D]>}`;
5
+ }[keyof T & string];
6
+ /**
7
+ * Every dot path of `T`: its keys, then the keys of its values, and so on.
8
+ *
9
+ * - String keys only. Arrays and tuples use `${number}`.
10
+ * - Optional values are followed. `Date`, functions, `Map`, `Set` and other built-ins are not.
11
+ * - At most 9 segments (`a.0.b` has 3), only reached by self-referencing types.
12
+ *
13
+ * Needs TypeScript 4.1+.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * interface Settings {
18
+ * theme: { color: string };
19
+ * tags: string[];
20
+ * }
21
+ *
22
+ * type Path = Paths<Settings>; // 'theme' | 'theme.color' | 'tags' | `tags.${number}`
23
+ * ```
24
+ */
25
+ export type Paths<T> = PathsAt<T, 8>;
26
+ type Get<T, K extends string> = T extends null | undefined ? undefined : K extends keyof T ? T[K] : T extends ReadonlyArray<infer U> ? K extends `${number}` ? U : never : never;
27
+ /**
28
+ * The type at the dot path `P` of `T`. It includes `undefined` when a step of the path is optional,
29
+ * and is `never` when the path does not exist.
30
+ *
31
+ * Needs TypeScript 4.1+.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * interface Settings {
36
+ * theme: { color: string };
37
+ * owner?: { name: string };
38
+ * tags: string[];
39
+ * }
40
+ *
41
+ * type Color = PathValue<Settings, 'theme.color'>; // string
42
+ * type Owner = PathValue<Settings, 'owner.name'>; // string | undefined
43
+ * type Tag = PathValue<Settings, 'tags.0'>; // string
44
+ *
45
+ * function get<T, P extends Paths<T>>(value: T, path: P): PathValue<T, P> { ... }
46
+ * ```
47
+ */
48
+ export type PathValue<T, P extends string> = P extends `${infer Head}.${infer Rest}` ? PathValue<Get<T, Head>, Rest> : Get<T, P>;
49
+ export {};
@@ -0,0 +1,51 @@
1
+ type Delimiter = '_' | '-' | ' ';
2
+ type State = 'start' | 'lower' | 'upper' | 'delimiter';
3
+ type IsLower<C extends string> = C extends Lowercase<C> ? true : false;
4
+ type Piece<C extends string, Before extends State, Separator extends string> = C extends Delimiter ? '' : IsLower<C> extends true ? `${Before extends 'delimiter' ? Separator : ''}${C}` : `${Before extends 'delimiter' | 'lower' ? Separator : ''}${Lowercase<C>}`;
5
+ type NextState<C extends string, Before extends State> = C extends Delimiter ? Before extends 'start' ? 'start' : 'delimiter' : IsLower<C> extends true ? 'lower' : 'upper';
6
+ type Separate<S extends string, Separator extends string, Result extends string = '', Before extends State = 'start'> = S extends `${infer C}${infer Rest}` ? Separate<Rest, Separator, `${Result}${Piece<C, Before, Separator>}`, NextState<C, Before>> : Result;
7
+ /**
8
+ * `S` in kebab-case. Words are split on `_`, `-`, spaces and lowercase → uppercase changes.
9
+ * `string` stays `string`.
10
+ *
11
+ * Needs TypeScript 4.1+ (about 40 characters on TypeScript 4.1–4.4).
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * type A = KebabCase<'userId'>; // 'user-id'
16
+ * type B = KebabCase<'USER_ID'>; // 'user-id'
17
+ * type C = KebabCase<'UserID'>; // 'user-id'
18
+ * ```
19
+ */
20
+ export type KebabCase<S extends string> = string extends S ? string : Separate<S, '-'>;
21
+ /**
22
+ * `S` in snake_case. Words are split on `_`, `-`, spaces and lowercase → uppercase changes.
23
+ * `string` stays `string`.
24
+ *
25
+ * Needs TypeScript 4.1+ (about 40 characters on TypeScript 4.1–4.4).
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * type A = SnakeCase<'userId'>; // 'user_id'
30
+ * type B = SnakeCase<'user-name id'>; // 'user_name_id'
31
+ * ```
32
+ */
33
+ export type SnakeCase<S extends string> = string extends S ? string : Separate<S, '_'>;
34
+ type ToUnderscores<S extends string, Result extends string = ''> = S extends `${infer C}${infer Rest}` ? ToUnderscores<Rest, `${Result}${C extends Delimiter ? '_' : C}`> : Result;
35
+ type Word<W extends string> = W extends Uppercase<W> ? Capitalize<Lowercase<W>> : Capitalize<W>;
36
+ type JoinWords<S extends string, Result extends string = ''> = S extends `${infer W}_${infer Rest}` ? JoinWords<Rest, `${Result}${Word<W>}`> : `${Result}${Word<S>}`;
37
+ /**
38
+ * `S` in camelCase. Words are split on `_`, `-` and spaces; all-uppercase words are lowercased first.
39
+ * `string` stays `string`.
40
+ *
41
+ * Needs TypeScript 4.1+ (about 40 characters on TypeScript 4.1–4.4).
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * type A = CamelCase<'user_id'>; // 'userId'
46
+ * type B = CamelCase<'USER_ID'>; // 'userId'
47
+ * type C = CamelCase<'user-name id'>; // 'userNameId'
48
+ * ```
49
+ */
50
+ export type CamelCase<S extends string> = string extends S ? string : Uncapitalize<JoinWords<ToUnderscores<S>>>;
51
+ export {};
@@ -0,0 +1,15 @@
1
+ type BuildTuple<T, N extends number, Result extends unknown[] = []> = Result['length'] extends N ? Result : BuildTuple<T, N, [T, ...Result]>;
2
+ /**
3
+ * A tuple of `N` items of type `T`. `number` gives `T[]`; a negative or decimal `N` gives `never`;
4
+ * a union of lengths gives a union of tuples.
5
+ *
6
+ * Needs TypeScript 4.1+ (`N` up to 42 on TypeScript 4.1–4.4, 998 on TypeScript 4.5+).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * type Rgb = Tuple<number, 3>; // [number, number, number]
11
+ * type Pair = Tuple<string, 2>; // [string, string]
12
+ * ```
13
+ */
14
+ export type Tuple<T, N extends number> = number extends N ? T[] : N extends unknown ? `${N}` extends `-${string}` | `${string}.${string}` ? never : BuildTuple<T, N> : never;
15
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The intersection of all the members of the union `U`.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * type Both = UnionToIntersection<{ id: number } | { name: string }>; // { id: number } & { name: string }
7
+ * ```
8
+ */
9
+ export type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
10
+ /**
11
+ * `T` or any other `Base` (`string` by default), keeping editor autocomplete for the members of `T`.
12
+ * A plain `'sm' | 'md' | string` collapses to `string` and loses the suggestions.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * type Size = LiteralUnion<'sm' | 'md' | 'lg'>;
17
+ *
18
+ * const a: Size = 'md'; // suggested
19
+ * const b: Size = 'xl'; // allowed
20
+ * const c: Size = 1; // error
21
+ * ```
22
+ */
23
+ export type LiteralUnion<T extends Base, Base = string> = T | (Base & Record<never, never>);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ashetm/types",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "Small, dependency-free TypeScript utility types (Nullable, NonEmptyArray, DeepPartial, Brand, Prettify, LiteralUnion, Merge, JsonValue, Paths, CamelCase, Tuple, ...). Types only: adds nothing to your bundle.",
5
5
  "contributors": [
6
6
  {
@@ -62,10 +62,17 @@
62
62
  "type": "module",
63
63
  "exports": {
64
64
  ".": {
65
- "types": "./dist/index.d.ts",
66
- "default": "./dist/index.js"
65
+ "import": {
66
+ "types": "./dist/index.d.ts",
67
+ "default": "./dist/index.js"
68
+ },
69
+ "require": {
70
+ "types": "./dist/index.d.cts",
71
+ "default": "./dist/index.cjs"
72
+ }
67
73
  }
68
74
  },
75
+ "main": "./dist/index.cjs",
69
76
  "module": "./dist/index.js",
70
77
  "types": "./dist/index.d.ts",
71
78
  "typesVersions": {
@@ -83,7 +90,7 @@
83
90
  "access": "public"
84
91
  },
85
92
  "scripts": {
86
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
93
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/build-cjs.mjs",
87
94
  "test": "tsc -p tsconfig.spec.json",
88
95
  "typecheck": "tsc -p tsconfig.json",
89
96
  "test:compat": "npm run build && sh compat/run.sh",