From 41e24a1e4f2705901702bdaeeb42d9349bb989e1 Mon Sep 17 00:00:00 2001 From: Rickard Andersson Date: Thu, 3 Aug 2023 10:53:58 +0300 Subject: [PATCH] feat(dev): add `assertUnreachable` Asserts that a case is unreachable in `switch` statements (and really any flow control construct) --- src/utilities.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/utilities.ts diff --git a/src/utilities.ts b/src/utilities.ts new file mode 100644 index 00000000..5ab5221e --- /dev/null +++ b/src/utilities.ts @@ -0,0 +1,18 @@ +/** + * Asserts that a case in a switch statement is unreachable. + * + * @example + * // Exhaustively checks `user.role` type ("admin" | "user") and will not compile + * // if a new role is added without adding a case to the switch statement. + * switch (user.role) { + * case "admin": + * break; + * case "user": + * break; + * default: + * assertUnreachable(user.role); + * } + */ +export function assertUnreachable(value: never): never { + throw new Error(`Unreachable case: ${value}`); +}