mirror of
https://github.com/denoland/std.git
synced 2024-11-21 20:50:22 +00:00
de9f8d2db1
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>
37 lines
677 B
TypeScript
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);
|
|
});
|