this function throws an error whenever called, and it logs the messages that you've provided it,
in (almost) the same manner as console.log would do.
Tip
where is this function useful?
suppose you want to ensure that the value returned by a function my_fn: <T>() => (T | undefined) is non-nullable.
and if it is undefined, then the your current function scope to throw an error, so that it exits.
typically, you would have to do something like:
// example 1: constmy_var = my_fn() if(my_var === undefined || my_var === null) { throwError("`my_var` was not supposed to be undefined") }
// example 2: constmy_path = normalizePath("path/to/file.ts") if(!my_path.startsWith("./")) { throwError(`expected a relative path, instead found: ${my_path}`) }
but with this function, you can write more concise inline statements for invoking errors conditionally:
// example 1: constmy_var = (my_fn() ?? throw_error("`my_var` was not supposed to be undefined"))!
// example 2: const temp = normalizePath("path/to/file.ts"), my_path = (temp.startsWith("./") ? temp : throw_error("expected a relative path, found:", temp))!
Example
import { assertThrows } from"jsr:@std/assert"
assertThrows(throw_error, "")
assertThrows(() => { constmy_fn = ((): string | undefined=> (undefined)) constmy_var = (my_fn() ?? throw_error("`my_var` was not supposed to be undefined"))! typeofmy_varsatisfiesstring }, "`my_var` was not supposed to be undefined")
this function throws an error whenever called, and it logs the
messages
that you've provided it, in (almost) the same manner asconsole.log
would do.where is this function useful?
suppose you want to ensure that the value returned by a function
my_fn: <T>() => (T | undefined)
is non-nullable. and if it isundefined
, then the your current function scope to throw an error, so that it exits.typically, you would have to do something like:
but with this function, you can write more concise inline statements for invoking errors conditionally:
Example