std/assert/never_test.ts
Yusuke Tanaka de9f8d2db1
feat(assert/unstable): add assertNever (#5690)
This commit adds a new function `assertNever` to the `assert` submodule.

This function is particularly useful when we want to check whether we properly
handle all the variants of a discriminated union. Ref:
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-exhaustiveness-checking

---------

Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
2024-08-16 08:10:23 -07:00

37 lines
677 B
TypeScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { AssertionError, assertNever, assertThrows } from "./mod.ts";
Deno.test("assertNever: exhaustiveness check", () => {
type Kinds = "A" | "B";
function doA() {
// ...
}
function doB() {
// ...
}
function handleKind(kind: Kinds) {
switch (kind) {
case "A":
doA();
break;
case "B":
doB();
break;
default:
assertNever(kind);
}
}
handleKind("A");
handleKind("B");
});
Deno.test("assertNever throws AssertionError", () => {
assertThrows(() => {
assertNever(42 as never);
}, AssertionError);
});