std/assert/assert.ts

24 lines
681 B
TypeScript
Raw Permalink Normal View History

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import { AssertionError } from "./assertion_error.ts";
/**
* Make an assertion, error will be thrown if `expr` does not have truthy value.
*
* @example Usage
* ```ts no-eval
* import { assert } from "@std/assert";
*
* assert("hello".includes("ello")); // Doesn't throw
* assert("hello".includes("world")); // Throws
* ```
*
* @param expr The expression to test.
* @param msg The optional message to display if the assertion fails.
*/
export function assert(expr: unknown, msg = ""): asserts expr {
if (!expr) {
throw new AssertionError(msg);
}
}