-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unreachable.ts
71 lines (67 loc) · 1.58 KB
/
unreachable.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
/**
* Error indicating that this part is unreachable.
*/
export class UnreachableError extends Error {
readonly args: unknown[];
constructor(args: unknown[]) {
super(`unreachable: ${args}`);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnreachableError);
}
this.name = this.constructor.name;
this.args = args;
}
}
/**
* Function indicating that this part is unreachable.
*
* For example, the following code passed type checking.
*
* ```ts
* import { unreachable } from "@core/errorutil/unreachable";
*
* type Animal = "dog" | "cat";
*
* function say(animal: Animal): void {
* switch (animal) {
* case "dog":
* console.log("dog");
* break;
* case "cat":
* console.log("dog");
* break;
* default:
* unreachable(animal);
* }
* }
* say("dog");
* ```
*
* But the following code because a case for "bird" is missing.
*
* ```ts
* import { unreachable } from "@core/errorutil/unreachable";
*
* type Animal = "dog" | "cat" | "bird";
*
* function say(animal: Animal): void {
* switch (animal) {
* case "dog":
* console.log("dog");
* break;
* case "cat":
* console.log("dog");
* break;
* default: {
* // The line below causes a type error if we uncomment it.
* // error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'never'.
* //unreachable(animal);
* }
* }
* }
* say("dog");
* ```
*/
export function unreachable(...args: never[]): never {
throw new UnreachableError(args);
}