@quentinadam/ensure
v0.1.6
Published
A simple function that asserts that a value is not undefined or null and returns the narrowed value
Readme
@quentinadam/ensure
A simple function that asserts that a value is not undefined or null and returns the narrowed value.
Usage
import { AssertionError, ensure } from '@quentinadam/ensure';
const a = ensure(1); // returns 1
try {
const b = ensure(undefined);
} catch (e) {
// throws AssertionError
}
try {
const c = ensure(undefined, 'Value is required');
} catch (e) {
// throws AssertionError with custom message
}
try {
const d = ensure(undefined, new Error('Value is required'));
} catch (e) {
// throws a custom Error
}
const value: string | undefined = 'hello';
const narrowedValue = ensure(value); // narrows the type to string
narrowedValue.toUpperCase(); // works