@ashetm/types 1.0.0 → 1.1.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
@@ -15,7 +15,7 @@ npm install @ashetm/types
15
15
  ## API
16
16
 
17
17
  ```ts
18
- import type { ArrayItem, Brand, DeepPartial, DeepReadonly, KeysOfType, Maybe, Mutable, NonEmptyArray, Nullable, ValueOf } from '@ashetm/types';
18
+ import type { DeepPartial, NonEmptyArray, Nullable, Prettify /* , ... */ } from '@ashetm/types';
19
19
  ```
20
20
 
21
21
  On TypeScript 3.7, use `import { ... }` (`import type` needs TypeScript 3.8).
@@ -48,6 +48,12 @@ type Role = ArrayItem<readonly ['admin', 'user']>; // 'admin' | 'user'
48
48
  | `ValueOf<T>` | the union of the value types of `T`. |
49
49
  | `KeysOfType<T, V>` | the keys of `T` whose value is assignable to `V` (`undefined` is ignored). |
50
50
  | `Mutable<T>` | `T` without `readonly` on its properties (one level, arrays and tuples too). |
51
+ | `Prettify<T>` | `T` with its intersections flattened, so hovers are readable (`readonly` and `?` kept). |
52
+ | `PartialBy<T, K>` | `T` with only the keys `K` optional. |
53
+ | `RequiredBy<T, K>` | `T` with only the keys `K` required. |
54
+ | `RequireAtLeastOne<T, K>` | at least one of the keys `K` (all keys by default) must be set. |
55
+ | `RequireExactlyOne<T, K>` | exactly one of the keys `K` (all keys by default) must be set, the others are not allowed. |
56
+ | `SplitKeys<T>` | a union with one object type per key of `T` (`readonly` and `?` kept). |
51
57
 
52
58
  ```ts
53
59
  const Status = { Active: 'active', Archived: 'archived' } as const;
@@ -59,6 +65,29 @@ interface User {
59
65
  nickname?: string;
60
66
  }
61
67
  type TextKeys = KeysOfType<User, string>; // 'name' | 'nickname'
68
+ type NewUser = PartialBy<User, 'id'>; // { name: string; nickname?: string; id?: number }
69
+
70
+ interface Contact {
71
+ name: string;
72
+ email?: string;
73
+ phone?: string;
74
+ }
75
+ type Reachable = RequireAtLeastOne<Contact, 'email' | 'phone'>;
76
+ const contact: Reachable = { name: 'A' }; // error: email or phone is needed
77
+
78
+ type Change = SplitKeys<{ name: string; age?: number }>; // { name: string } | { age?: number }
79
+ ```
80
+
81
+ TypeScript can't split an intersection back into its members, so there is no `IntersectionToUnion`: `SplitKeys<A & B>` gives `A | B` only when `A` and `B` have one key each.
82
+
83
+ ### Unions
84
+
85
+ | Type | Is |
86
+ |--------------------------|-------------------------------------------------|
87
+ | `UnionToIntersection<U>` | the intersection of all the members of `U`. |
88
+
89
+ ```ts
90
+ type Both = UnionToIntersection<{ id: number } | { name: string }>; // { id: number } & { name: string }
62
91
  ```
63
92
 
64
93
  ### Deep types
@@ -67,11 +96,13 @@ type TextKeys = KeysOfType<User, string>; // 'name' | 'nickname'
67
96
  |-------------------|--------------------------------------------------------|
68
97
  | `DeepPartial<T>` | `T` with every property optional, at every level. |
69
98
  | `DeepReadonly<T>` | `T` with every property `readonly`, at every level. |
99
+ | `DeepRequired<T>` | `T` with every property required, at every level. |
100
+ | `DeepMutable<T>` | `T` without `readonly`, at every level. |
70
101
 
71
- Both of them:
102
+ All of them:
72
103
 
73
- - go into arrays and tuples (tuples keep their length; `DeepReadonly` makes them readonly),
74
- - go into `Map` and `Set` values (`Map` keys are kept; `DeepReadonly` turns them into `ReadonlyMap` and `ReadonlySet`),
104
+ - go into arrays and tuples (tuples keep their length; `DeepReadonly` / `DeepMutable` make them readonly / mutable; `DeepRequired` makes optional tuple items required),
105
+ - go into `Map` and `Set` values (`Map` keys are kept; `DeepReadonly` gives `ReadonlyMap` / `ReadonlySet`, `DeepMutable` gives `Map` / `Set`),
75
106
  - keep primitives, functions, `Date`, `RegExp`, `Error`, `Promise`, `WeakMap` and `WeakSet` as they are.
76
107
 
77
108
  ```ts
@@ -87,6 +118,24 @@ settings.theme.color = 'blue'; // error
87
118
  settings.tags.push('a'); // error
88
119
  ```
89
120
 
121
+ `DeepRequired` removes `?` with the `undefined` that came with it; an explicit `| undefined` is kept.
122
+
123
+ ### JSON
124
+
125
+ | Type | Is |
126
+ |-----------------|------------------------------------------------------|
127
+ | `JsonPrimitive` | `string \| number \| boolean \| null` |
128
+ | `JsonValue` | any JSON value: what `JSON.parse` can return. |
129
+ | `JsonObject` | `{ [key: string]: JsonValue }` |
130
+ | `JsonArray` | `JsonValue[]` |
131
+
132
+ ```ts
133
+ const payload: JsonValue = { id: 1, tags: ['a'], meta: null };
134
+ const invalid: JsonValue = { at: new Date() }; // error
135
+ ```
136
+
137
+ An `interface` has no index signature, so a value typed with one is not assignable to `JsonObject`: use a `type` instead.
138
+
90
139
  ### Branded types
91
140
 
92
141
  `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.
package/dist/deep.d.ts CHANGED
@@ -43,4 +43,47 @@ export type DeepPartial<T> = T extends Map<infer K, infer V> ? Map<K, DeepPartia
43
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
44
  readonly [K in keyof T]: DeepReadonly<T[K]>;
45
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
+ };
46
89
  export {};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from './array.js';
2
2
  export * from './brand.js';
3
3
  export * from './deep.js';
4
+ export * from './json.js';
4
5
  export * from './nullable.js';
5
6
  export * from './object.js';
7
+ export * from './union.js';
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from './array.js';
2
2
  export * from './brand.js';
3
3
  export * from './deep.js';
4
+ export * from './json.js';
4
5
  export * from './nullable.js';
5
6
  export * from './object.js';
7
+ export * from './union.js';
package/dist/json.d.ts ADDED
@@ -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[];
package/dist/json.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/object.d.ts CHANGED
@@ -44,3 +44,104 @@ export type KeysOfType<T, V> = {
44
44
  export type Mutable<T> = {
45
45
  -readonly [K in keyof T]: T[K];
46
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];
@@ -0,0 +1,9 @@
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;
package/dist/union.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ashetm/types",
3
- "version": "1.0.0",
4
- "description": "Small, dependency-free TypeScript utility types (Nullable, Maybe, NonEmptyArray, DeepPartial, DeepReadonly, Brand, ...). Types only: adds nothing to your bundle.",
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.",
5
5
  "contributors": [
6
6
  {
7
7
  "email": "contact@ashetm.com",
@@ -19,15 +19,22 @@
19
19
  "branded-types",
20
20
  "deep-partial",
21
21
  "deep-readonly",
22
+ "deep-required",
23
+ "json",
22
24
  "maybe",
23
25
  "mutable",
24
26
  "nominal-types",
25
27
  "non-empty-array",
26
28
  "nullable",
29
+ "partial-by",
30
+ "prettify",
31
+ "require-at-least-one",
32
+ "require-exactly-one",
27
33
  "ts",
28
34
  "type-utilities",
29
35
  "types",
30
36
  "typescript",
37
+ "union-to-intersection",
31
38
  "utility-types"
32
39
  ],
33
40
  "license": "MIT",