Skip to content

Commit 3a668e2

Browse files
committed
Rework Complex Union Type Example
Hail the Optional monad... Kind of 🤡
1 parent 20bcd1d commit 3a668e2

File tree

4 files changed

+57
-58
lines changed

4 files changed

+57
-58
lines changed

examples/04-complex-union-types/complex-union-types.test.ts

Lines changed: 0 additions & 32 deletions
This file was deleted.

examples/04-complex-union-types/complex-union-types.ts

Lines changed: 0 additions & 26 deletions
This file was deleted.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { Some, None, Optional } from './more-complex-types';
2+
const noop = () => {};
3+
4+
describe('More Complex Types: OptionalPattern', () => {
5+
it('should match a Some with Some(value)', () => {
6+
const someSpy = jest.fn();
7+
const noneSpy = jest.fn();
8+
const value = 'I have a value';
9+
const optional: Optional<string> = new Some(value);
10+
11+
optional.match({
12+
Some: someSpy,
13+
None: noneSpy
14+
});
15+
16+
expect(someSpy).toHaveBeenCalledWith(value);
17+
expect(noneSpy).not.toHaveBeenCalled();
18+
});
19+
20+
it('should match a None with None()', () => {
21+
const someSpy = jest.fn();
22+
const noneSpy = jest.fn();
23+
const optional: Optional<string> = new None<string>();
24+
25+
optional.match({
26+
Some: someSpy,
27+
None: noneSpy
28+
});
29+
30+
expect(someSpy).not.toHaveBeenCalled();
31+
expect(noneSpy).toHaveBeenCalled();
32+
});
33+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export type Optional<T> = Some<T> | None<T>;
2+
3+
interface OptionalPattern<T> {
4+
Some: (d: T) => T;
5+
None: () => T;
6+
}
7+
8+
interface OptionalMatcher {
9+
match<T>(p: OptionalPattern<T>): T;
10+
}
11+
12+
export class Some<T> implements OptionalMatcher {
13+
constructor(private readonly value: T) {}
14+
15+
match(p: OptionalPattern<T>): T {
16+
return p.Some(this.value);
17+
}
18+
}
19+
20+
export class None<T> implements OptionalMatcher {
21+
match(p: OptionalPattern<T>): T {
22+
return p.None();
23+
}
24+
}

0 commit comments

Comments
 (0)