Function: assertNonNullable()
API / @xmachines/play / assertNonNullable
function assertNonNullable<V>(value, name?): NonNullable<V>;Defined in: packages/play/src/utils.ts:39
Asserts that value is not null and not undefined, then returns it with the
type NonNullable<V>. One expression therefore holds the guard and the narrowed
value.
A non-null assertion (value!) is different: it produces undefined, and your
code then fails later with a message such as “undefined is not an object”. This
function throws a clear error at the point of the failure.
An assertion function of the form asserts value is T is also different: this
function returns the narrowed value directly. Therefore the call site needs no
second variable and no as cast.
Type Parameters
| Type Parameter |
|---|
V |
Parameters
| Parameter | Type | Description |
|---|---|---|
value | V | The value to check. |
name? | string | The optional name in the error message. It identifies the missing value, for example the name of the variable or of the injection key. |
Returns
NonNullable<V>
value with the type NonNullable<V>, without null and without undefined.
Throws
When value is null or undefined.
Example
import { assertNonNullable } from "@xmachines/play";
// inject() and assertNonNullable in one line, with no `!` and no second variable:const actor = assertNonNullable(inject<AuthActor>("actor"), "actor");
// A lookup of an element:const el = assertNonNullable(document.getElementById("app"), "#app");