-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption.ts
69 lines (59 loc) · 1.48 KB
/
option.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
/**
* Represents an optional value.
*/
export interface Option<T> {
/**
* Returns the contained `Some` value.
*/
unwrap(): T;
/**
* Returns the contained `Some` value or a default.
*/
unwrapOr(defaultValue: T): T;
/**
* Returns `true` if the option is a `Some` value.
*/
isSome(): this is SomeOption<T>;
/**
* Returns `true` if the option is a `None` value.
*/
isNone(): this is NoneOption;
}
type SomeOption<T> = Option<T>;
type NoneOption = Option<never>;
class OptionImpl<T> implements Option<T> {
private constructor(private value?: T) {}
public unwrap(): T {
if (this.isSome()) return this.value as T;
throw new Error(`called \`unwrap()\` on a \`None\` value`);
}
public unwrapOr(defaultValue: T): T {
return this.isSome() ? (this.value as T) : defaultValue;
}
public isSome(): this is SomeOption<T> {
return this.value !== undefined;
}
public isNone(): this is NoneOption {
return this.value === undefined;
}
/**
* Creates a new `Some` option.
*/
public static some<T>(value: T): SomeOption<T> {
return new OptionImpl(value);
}
/**
* Creates a new `None` option.
*/
public static none(): NoneOption {
return new OptionImpl();
}
}
/**
* Creates a new `Some` option.
*/
export const Some = OptionImpl.some;
/**
* Creates a new `None` option.
*/
export const None = OptionImpl.none();