-
Notifications
You must be signed in to change notification settings - Fork 1
/
README.ts
736 lines (596 loc) · 15 KB
/
README.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*!
<div align="center">
# unenum
**Universal ADT utilities for TypeScript.**
[Installation](#installation) • [`Enum`](#enum) • [`builder`](#builder) •
[`is`](#is) • [`match`](#match) • [`Result`](#result) •
[`Result.from`](#resultfrom) • [`Async`](#async)
</div>
- produces simple and portable discriminated union types.
- all types can be compiled away, with zero-cost to bundle size.
- supports custom discriminants for type utilities and runtime helpers.
- includes `Result` to improve error-handling ergonomics.
- includes helpers to inspect/pick/omit/merge/extend Enums and variants.
- includes optional runtime helpers, `is`, `match` and `Result.from`.
Read more:
- [Tagged union](https://wikipedia.org/wiki/Tagged_union)
- [Algebraic data type](https://wikipedia.org/wiki/Algebraic_data_type)
- [Comparison of programming languages (algebraic data type)](https://wikipedia.org/wiki/Comparison_of_programming_languages_(algebraic_data_type))
## Installation
[![Version](https://img.shields.io/npm/v/unenum?label=npm)](https://www.npmjs.com/package/unenum/)
[![License](https://img.shields.io/npm/l/unenum)](./LICENSE)
```shell
npm install unenum
```
```shell
yarn add unenum
```
### Requirements
- `typescript@>=5.0.0`
- `tsconfig.json > "compilerOptions" > { "strict": true }`
## Playground
- This `README.ts` is a valid TypeScript file!
1. Clone this repo: `git clone [email protected]:peterboyer/unenum.git`.
2. Install development dependencies: `npm install` or `yarn install`.
3. Jump in and experiment!
!*/
/*!
## `Enum`
!*/
//>
import { type Enum } from "unenum";
//<
/*!
### Defining an Enum
- The `_type` property is used as discriminant to distinguish between variants.
- The underscore-prefixed name somewhat denotes this as a special property not
intended to collide with general-use user-space named properties.
!*/
//>
export type User = Enum<{
Anonymous: true;
Authenticated: { userId: string };
}>;
// | { _type: "Anonymous" }
// | { _type: "Authenticated", userId: string }
//<
/*!
### Instantiating an Enum
!*/
/*!
#### (a) builder function
- [`builder`](#builder) creates an Enum value "constructor" typed with a given
Enum type.
- You may define and export the builder with the same name
as your Enum's type.
!*/
//>
export const User = builder({} as User);
{
const user: User = User.Anonymous();
void user;
void (() => User.Anonymous());
void (() => User.Authenticated({ userId: "..." }));
}
//<
/*!
#### (b) object expression
- Alternatively, you may chose to not use a builder.
!*/
//>
{
const user: User = { _type: "Anonymous" };
void user;
void ((): User => ({ _type: "Anonymous" }));
void ((): User => ({ _type: "Authenticated", userId: "..." }));
}
//<
/*!
### Using an Enum
!*/
/*!
#### (a.1) if statements, type-guard helper
- [`is`](#is) also allows for matching using an array of multiple variants' keys.
!*/
//>
(function (user: User): string {
if (is(user, "Authenticated")) {
return `Logged in as ${user.userId}.`;
}
return "Not logged in.";
});
//<
/*!
#### (a.2) if statements, property access
- Alternatively, you may chose to not use a matcher.
!*/
//>
(function (user: User): string {
if (user._type === "Authenticated") {
return `Logged in as ${user.userId}.`;
}
return "Not logged in.";
});
//<
/*!
#### (b.1) match helper, handling all cases
- [`match`](#match) allows easy type safe mapping of variants and variants'
values to another returned value.
!*/
//>
(function (user: User): string {
return match(user, {
Authenticated: ({ userId }) => `Logged in as ${userId}.`,
Anonymous: "Not logged in.",
});
});
//<
/*!
#### (b.2) match helper, with catch-all
!*/
//>
(function (user: User): string {
return match(user, {
Authenticated: ({ userId }) => `Logged in as ${userId}.`,
_: "Unhandled case.",
});
});
//<
/*!
### `builder`
- Returns a constructor based on the given Enum type to easily create variant
object values.
- A custom "mapper" can be used to define functions per Enum variant to
streamline construction of Enum variants based on your use-cases.
!*/
//>
type Colour = Enum<{
Transparent: true;
Named: { name: string };
RGB: Record<"r" | "g" | "b", number>;
}>;
export const Colour = builder({} as Colour, {
RGB: (r: number, g: number, b: number) => ({ r, g, b }),
});
{
const color: Colour = Colour.RGB(4, 2, 0);
void color;
// variant with no properties
void ((): Colour => Colour.Transparent());
// variant with properties
void ((): Colour => Colour.Named({ name: "Red" }));
// variant with mapper function
void ((): Colour => Colour.RGB(0, 0, 0));
}
//<
//>
import { builder } from "unenum";
//<
/*!
### `is`
- Returns `true` and narrows the given Enum value's possible variants if the
value matches any of the specified variants by key.
!*/
//>
import { is } from "unenum";
{
type Value = Enum<{ A: true; B: { value: string } }>;
const value = {} as Value;
void (() => is(value, "A"));
void (() => is(value, "B"));
void (() => is(value, ["A"]));
void (() => is(value, ["A", "B"]));
}
//<
//>
import { is_ } from "unenum";
{
type Value = Enum<{ A: true; B: { value: string } }, "custom">;
const value = {} as Value;
void (() => is_(value, "custom", "A"));
void (() => is_(value, "custom", "B"));
void (() => is_(value, "custom", ["A"]));
void (() => is_(value, "custom", ["A", "B"]));
}
//<
/*!
### `match`
- The `matcher` object is keyed with all possible variants of the Enum and an
optional `_` fallback case.
- If the `_` fallback case is not given, _all_ variants must be specified.
- All `matcher` cases (including `_`) can be a value or a callback.
- If a variant's case is a callback, the matching variants value's properties
are available for access.
!*/
//>
import { match } from "unenum";
{
const value = {} as Enum<{ A: true; B: { value: string } }>;
void (() => match(value, { _: "Fallback" }));
void (() => match(value, { _: () => "Fallback" }));
void (() => match(value, { A: "A", _: "Fallback" }));
void (() => match(value, { A: () => "A", _: "Fallback" }));
void (() => match(value, { A: "A", B: "B" }));
void (() => match(value, { A: "A", B: () => "B" }));
void (() => match(value, { A: () => "A", B: () => "B" }));
void (() => match(value, { A: () => "A", B: () => "B", _: "Fallback" }));
void (() => match(value, { A: undefined, B: ({ value }) => value }));
void (() => match(value, { B: ({ value }) => value, _: "Fallback" }));
void (() => match(value, { A: true, B: false, _: undefined }));
}
//<
//>
import { match_ } from "unenum";
{
const value = {} as Enum<{ A: true; B: { value: string } }, "custom">;
void (() => match_(value, "custom", { _: "Fallback" }));
void (() => match_(value, "custom", { A: "A", B: "B" }));
void (() => match_(value, "custom", { A: "A", _: "Fallback" }));
// ...
}
//<
/*!
### Manipulating an Enum
- These utilities as available as part of the `Enum` type import's namespace.
- All of these Enum type utilities support a custom discriminant as the last
type parameter, e.g. `Enum.Root<Signal, "custom">`.
!*/
//>
// example
type Signal = Enum<{ Red: true; Yellow: true; Green: true }>;
//<
/*!
#### `Enum.Root`
- Infers a key/value mapping of an Enum's variants.
!*/
//>
export type Root = Enum.Root<Signal>;
// { Red: true, Yellow: true; Green: true }
//<
/*!
#### `Enum.Keys`
- Infers all keys of an Enum's variants.
!*/
//>
export type Keys = Enum.Keys<Signal>;
// "Red" | "Yellow" | "Green"
//<
/*!
#### `Enum.Pick`
- Pick subset of an Enum's variants by key.
!*/
//>
export type PickRed = Enum.Pick<Signal, "Red">;
// *Red
export type PickRedYellow = Enum.Pick<Signal, "Red" | "Yellow">;
// *Red | *Yellow
//<
/*!
#### `Enum.Omit`
- Omit subset of an Enum's variants by key.
!*/
//>
export type OmitRed = Enum.Omit<Signal, "Red">;
// *Yellow | *Green
export type OmitRedYellow = Enum.Omit<Signal, "Red" | "Yellow">;
// *Green
//<
/*!
#### `Enum.Extend`
- Add new variants and merge new properties for existing variants for an Enum.
!*/
//>
export type Extend = Enum.Extend<Signal, { Flashing: true }>;
// *Red | *Yellow | *Green | *Flashing
//<
/*!
#### `Enum.Merge`
- Merge all variants and properties of all given Enums.
!*/
//>
export type Merge = Enum.Merge<Enum<{ Left: true }> | Enum<{ Right: true }>>;
// *Left | *Right
//<
/*!
### Enums with custom discriminants
- Instead of using the default discriminant, all types and utilities can
specify a custom discriminant as an optional argument.
!*/
/*!
#### Defining
!*/
//>
export type File = Enum<
{
"text/plain": { data: string };
"image/jpeg": { data: Buffer; compression?: number };
"application/json": { data: unknown };
},
"mime" /* <-- */
>;
//<
/*!
#### Instantiating
!*/
/*!
##### (a) builder function
- Use `builder_` which requires the discriminant to be passed as an argument.
!*/
//>
import { builder_ } from "unenum";
export const File = builder_({} as File, "mime" /* <-- */);
{
const file: File = File["text/plain"]({ data: "..." });
void file;
void (() => File["text/plain"]({ data: "..." }));
void (() => File["image/jpeg"]({ data: Buffer.from("...") }));
void (() => File["application/json"]({ data: JSON.parse("{}") }));
}
//<
/*!
##### (b) object expression
!*/
//>
{
const file: File = { mime: "text/plain", data: "..." };
void file;
void ((): File => ({ mime: "text/plain", data: "..." }));
void ((): File => ({ mime: "image/jpeg", data: Buffer.from("...") }));
void ((): File => ({ mime: "application/json", data: JSON.parse("{}") }));
}
//<
/*!
#### Using
!*/
/*!
#### (a.1) if statements, type-guard helper
- Use `is_` which requires the discriminant to be passed as an argument.
!*/
//>
(function (file: File): string {
if (is_(file, "mime" /* <-- */, "text/plain")) {
return `Text`;
}
if (is_(file, "mime" /* <-- */, "image/jpeg")) {
return "Image";
}
return "Unsupported";
});
//<
/*!
#### (a.2) if statements, property access
!*/
//>
(function (file: File): string {
if (file.mime /* <-- */ === "text/plain") {
return `Text`;
}
if (file.mime /* <-- */ === "image/jpeg") {
return "Image";
}
return "Unsupported";
});
//<
/*!
#### (b) match helper
- Use `match_` which requires the discriminant to be passed as an argument.
!*/
//>
(function (file: File): string {
return match_(file, "mime" /* <-- */, {
"text/plain": () => "Text",
"image/jpeg": () => "Image",
_: () => "Unsupported",
});
});
//<
/*!
## `Result`
- Represents either a success "value" (`Result.Ok`) or a failure "error"
(`Result.Error`).
!*/
//>
import { Result } from "unenum";
//<
/*!
### Result without a value or error.
!*/
//>
(function (): Result {
if (Math.random()) {
return Result.Error();
}
return Result.Ok();
});
//<
/*!
### Result with a "value" and/or "error"
- `never` may be used for either `Value` or `Error` parameters if only the base
variant is needed without any value.
!*/
//>
(function (): Result<User, "NotFound"> {
const user = {} as User | undefined;
if (!user) {
return Result.Error("NotFound");
}
return Result.Ok(user);
});
//<
/*!
### Using a Result value
!*/
/*!
#### (a) narrowing
!*/
//>
(async function (): Promise<User | undefined> {
const $user = await (async () => ({}) as Promise<Result<User>>)();
// handle error
if (is($user, "Error")) {
return undefined;
}
// continue with value
const user = $user.value;
return user;
});
//<
/*!
#### (b) matching
!*/
//>
(async function (): Promise<User | undefined> {
const $user = await (async () => ({}) as Promise<Result<User>>)();
return match($user, {
Ok: ({ value: user }) => user,
Error: undefined,
});
});
//<
/*!
#### (c) value or `undefined` by property access
- The `Result` type defines both `value` and `error` properties in both
`Result.Ok` and `Result.Error` variants, however either variant sets the value
of the other as an falsy optional `never` property.
- This allows some cases where if your value is always truthy, you can skip
type narrowing by accepting `undefined` as the properties possible states.
!*/
//>
(async function (): Promise<User | undefined> {
const $user = await (async () => ({}) as Promise<Result<User>>)();
const user = $user.value;
// User | undefined
return user;
});
//<
/*!
### `Result.from`
- Instead of wrapping code that could `throw` in `try`/`catch` blocks,
`Result.from` can execute a given callback and return a `Result` wrapped value
without interrupting a function's control flow or scoping of variables.
- If the function throws then the `Error` Result variant is returned, otherwise
the `Ok` Result variant is returned.
- The `error` property will always be typed as `unknown` because
(unfortunately) in JavaScript, anything from anywhere can be thrown as an
error.
!*/
//>
const getValueOrThrow = (): string => {
if (Math.random()) {
throw new Error("Failure");
}
return "Success";
};
(function () {
const result = Result.from(() => getValueOrThrow());
// Result<string, unknown>
if (is(result, "Error")) {
// handle error
console.error(result.error);
return;
}
// (safely) continue with value
console.info(result.value);
});
//<
/*!
## `Async`
- Represents an asynchronous value that is either loading (`Pending`) or
resolved (`Ready`). If defined with an `Enum` type, `Async` will omit its
`Ready` variant in favour of the "non-pending" `Enum`'s variants.
- Useful for representing states e.g. `use*` hooks.
!*/
//>
import { Async } from "unenum";
//<
/*!
### Async without a value
!*/
//>
(function (): Async {
if (Math.random()) {
return Async.Pending();
}
return Async.Ready();
});
//<
/*!
### Async with a non-Enum value
!*/
//>
const useDeferredName = (): string | undefined => undefined;
(function useName(): Async<string> {
const name = useDeferredName();
if (!name) {
return Async.Pending();
}
return Async.Ready(name);
});
//<
/*!
### Async with a Enum value
- Which extends the given Enum value type with Async's `Pending` variant.
- You can use both `Async` and `Result` helpers together.
!*/
//>
const useResource = <T>() => [{} as T | undefined, { loading: false }] as const;
(function useUser(): Async<Result<User, "NotFound">> {
const [user, { loading }] = useResource<User | null>();
if (loading) {
return Async.Pending();
}
if (!user) {
return Result.Error("NotFound");
}
return Result.Ok(user);
});
//<
/*!
### Using a Async value
!*/
/*!
#### (a) narrowing
!*/
//>
(function Component(): string {
const $user = (() => ({}) as Async<Result<User, "E">>)();
if (is($user, "Pending")) {
return `<Loading />`;
}
// handle error
if (is($user, "Error")) {
const { error } = $user;
return `<Error error=${error} />`;
}
// continue with value
const user = $user.value;
return `<Profile user=${user} />`;
});
//<
/*!
#### (b) matching
!*/
//>
(function Component() {
const $user = (() => ({}) as Async<Result<User, unknown>>)();
return match($user, {
Pending: () => `<Loading />`,
Error: ({ error }) => `<Error error=${error} />`,
Ok: ({ value: user }) => `<Profile user=${user} />`,
});
});
//<
/*!
#### (c) value or undefined property access
!*/
//>
(function Component() {
const $user = (() => ({}) as Async<Result<User, "E">>)();
if (is($user, "Pending")) {
return `<Loading />`;
}
const user = $user.value;
// User | undefined
return `<Profile user=${user} />`;
});
//<