@ashetm/types 1.1.0 → 1.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/README.md CHANGED
@@ -1,9 +1,19 @@
1
1
  # @ashetm/types
2
2
 
3
- ``@ashetm/types`` is a small, dependency-free library of TypeScript utility types: nullability, arrays, objects, deep partial / readonly and branded types.
3
+ ``@ashetm/types`` is a small, dependency-free library of TypeScript utility types: nullability, arrays, objects, deep partial / readonly, JSON, dot paths, string cases and branded types.
4
4
 
5
5
  It is **types only**: it adds nothing to your bundle. It works with any project (Angular, React, Node, ...) on **TypeScript 3.7 or later**.
6
6
 
7
+ ## TypeScript support
8
+
9
+ | TypeScript | Angular | Types |
10
+ |------------|-------------|-------------------------------------------------------------------------------------------|
11
+ | 3.7 – 4.0 | 9 – 11.0 | all except [Paths](#paths) and [String cases](#string-cases) |
12
+ | 4.1 – 4.4 | 11.1 – 13.0 | all; string cases up to about 40 characters, `Paths` of self-referencing types up to 9 segments |
13
+ | 4.5+ | 13.1+ | all |
14
+
15
+ Your TypeScript version picks the right types by itself (`typesVersions`): nothing to configure.
16
+
7
17
  ## Install
8
18
 
9
19
  You can install it with npm:
@@ -136,6 +146,52 @@ const invalid: JsonValue = { at: new Date() }; // error
136
146
 
137
147
  An `interface` has no index signature, so a value typed with one is not assignable to `JsonObject`: use a `type` instead.
138
148
 
149
+ ### Paths
150
+
151
+ Needs TypeScript 4.1+.
152
+
153
+ | Type | Is |
154
+ |-------------------|--------------------------------------------------------------------------------------------|
155
+ | `Paths<T>` | every dot path of `T` (string keys; arrays and tuples use `${number}`). |
156
+ | `PathValue<T, P>` | the type at the dot path `P`: with `undefined` when a step is optional, `never` when the path does not exist. |
157
+
158
+ ```ts
159
+ interface Settings {
160
+ theme: { color: string };
161
+ owner?: { name: string };
162
+ tags: string[];
163
+ }
164
+
165
+ type Path = Paths<Settings>; // 'theme' | 'theme.color' | 'owner' | 'owner.name' | 'tags' | `tags.${number}`
166
+ type Owner = PathValue<Settings, 'owner.name'>; // string | undefined
167
+
168
+ declare const settings: Settings;
169
+ declare function get<T, P extends Paths<T>>(value: T, path: P): PathValue<T, P>;
170
+ get(settings, 'theme.color'); // string
171
+ get(settings, 'theme.size'); // error
172
+ ```
173
+
174
+ Optional values are followed; `Date`, functions, `Map`, `Set` and other built-ins are not. Self-referencing types (`children: Tree[]`) stop at 9 segments.
175
+
176
+ ### String cases
177
+
178
+ Needs TypeScript 4.1+.
179
+
180
+ | Type | Is |
181
+ |----------------|------------------------------------------------------------------------------------------|
182
+ | `CamelCase<S>` | `S` in camelCase: words split on `_`, `-` and spaces; all-uppercase words lowercased first. |
183
+ | `KebabCase<S>` | `S` in kebab-case: words split on `_`, `-`, spaces and lowercase → uppercase changes. |
184
+ | `SnakeCase<S>` | `S` in snake_case: same words as `KebabCase`. |
185
+
186
+ ```ts
187
+ type A = CamelCase<'user_id'>; // 'userId'
188
+ type B = CamelCase<'USER_ID'>; // 'userId'
189
+ type C = KebabCase<'userID'>; // 'user-id'
190
+ type D = SnakeCase<'user-name id'>; // 'user_name_id'
191
+ ```
192
+
193
+ `string` stays `string`, and a union is converted member by member.
194
+
139
195
  ### Branded types
140
196
 
141
197
  `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.
@@ -162,7 +218,8 @@ npm run test:compat
162
218
  ```
163
219
 
164
220
  - `npm test` type-checks the type tests (`src/*.spec-d.ts`): what must compile, and `// @ts-expect-error` for what must not. Nothing runs.
165
- - `npm run test:compat` builds, then checks `dist/*.d.ts` with TypeScript 3.7, 4.2, 5.0, 6 and the latest (downloaded with `npx`).
221
+ - `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`).
222
+ - `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.
166
223
 
167
224
  ## License
168
225
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,3 @@
1
- export * from './array.js';
2
- export * from './brand.js';
3
- export * from './deep.js';
4
- export * from './json.js';
5
- export * from './nullable.js';
6
- export * from './object.js';
7
- export * from './union.js';
1
+ export * from './legacy.js';
2
+ export * from './path.js';
3
+ export * from './string.js';
package/dist/index.js CHANGED
@@ -1,7 +1,3 @@
1
- export * from './array.js';
2
- export * from './brand.js';
3
- export * from './deep.js';
4
- export * from './json.js';
5
- export * from './nullable.js';
6
- export * from './object.js';
7
- export * from './union.js';
1
+ export * from './legacy.js';
2
+ export * from './path.js';
3
+ export * from './string.js';
@@ -0,0 +1,7 @@
1
+ export * from './array.js';
2
+ export * from './brand.js';
3
+ export * from './deep.js';
4
+ export * from './json.js';
5
+ export * from './nullable.js';
6
+ export * from './object.js';
7
+ export * from './union.js';
package/dist/legacy.js ADDED
@@ -0,0 +1,9 @@
1
+ // The types that work on TypeScript 3.7+. TypeScript < 4.1 reads only this file (`typesVersions` in `package.json`):
2
+ // keep template literal types and other TypeScript 4.1+ syntax out of it.
3
+ export * from './array.js';
4
+ export * from './brand.js';
5
+ export * from './deep.js';
6
+ export * from './json.js';
7
+ export * from './nullable.js';
8
+ export * from './object.js';
9
+ export * from './union.js';
package/dist/path.d.ts ADDED
@@ -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 {};
package/dist/path.js ADDED
@@ -0,0 +1,2 @@
1
+ // TypeScript 4.1+ only (template literal types): not exported from `legacy.ts`
2
+ 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 {};
package/dist/string.js ADDED
@@ -0,0 +1,3 @@
1
+ // TypeScript 4.1+ only (template literal types): not exported from `legacy.ts`.
2
+ // One recursion step per character, so TypeScript 4.1–4.4 handles strings of about 40 characters.
3
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ashetm/types",
3
- "version": "1.1.0",
4
- "description": "Small, dependency-free TypeScript utility types (Nullable, NonEmptyArray, DeepPartial, DeepReadonly, Brand, Prettify, RequireAtLeastOne, JsonValue, ...). Types only: adds nothing to your bundle.",
3
+ "version": "1.2.0",
4
+ "description": "Small, dependency-free TypeScript utility types (Nullable, NonEmptyArray, DeepPartial, Brand, Prettify, JsonValue, Paths, CamelCase, ...). Types only: adds nothing to your bundle.",
5
5
  "contributors": [
6
6
  {
7
7
  "email": "contact@ashetm.com",
@@ -17,19 +17,25 @@
17
17
  "keywords": [
18
18
  "angular",
19
19
  "branded-types",
20
+ "camel-case",
20
21
  "deep-partial",
21
22
  "deep-readonly",
22
23
  "deep-required",
24
+ "dot-path",
23
25
  "json",
26
+ "kebab-case",
24
27
  "maybe",
25
28
  "mutable",
26
29
  "nominal-types",
27
30
  "non-empty-array",
28
31
  "nullable",
29
32
  "partial-by",
33
+ "paths",
30
34
  "prettify",
31
35
  "require-at-least-one",
32
36
  "require-exactly-one",
37
+ "snake-case",
38
+ "template-literal-types",
33
39
  "ts",
34
40
  "type-utilities",
35
41
  "types",
@@ -56,6 +62,13 @@
56
62
  },
57
63
  "module": "./dist/index.js",
58
64
  "types": "./dist/index.d.ts",
65
+ "typesVersions": {
66
+ "<4.1": {
67
+ "*": [
68
+ "dist/legacy.d.ts"
69
+ ]
70
+ }
71
+ },
59
72
  "files": [
60
73
  "dist"
61
74
  ],