guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
46 lines (45 loc) • 1.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isDefined = void 0;
const generateTypeGuardError_1 = require("./generateTypeGuardError");
const isNil_1 = require("./isNil");
/**
* Checks if a value is not null and not undefined (is defined).
*
* This is the opposite of isNil - it returns true for any value that is not null or undefined.
*
* @param value - The value to check
* @param config - Optional configuration for error handling
* @returns True if the value is not null and not undefined, false otherwise
*
* @example
* ```typescript
* import { isDefined } from 'guardz';
*
* console.log(isDefined("hello")); // true
* console.log(isDefined(0)); // true
* console.log(isDefined(false)); // true
* console.log(isDefined("")); // true
* console.log(isDefined({})); // true
* console.log(isDefined([])); // true
* console.log(isDefined(null)); // false
* console.log(isDefined(undefined)); // false
*
* // Useful for filtering out null/undefined values
* const data: unknown = getUserInput();
* if (isDefined(data)) {
* // data is now typed as NonNullable<unknown>
* // TypeScript knows data is not null or undefined
* }
* ```
*/
const isDefined = function (value, config) {
if ((0, isNil_1.isNil)(value, null)) {
if (config) {
config.callbackOnError((0, generateTypeGuardError_1.generateTypeGuardError)(value, config.identifier, 'isDefined'));
}
return false;
}
return true;
};
exports.isDefined = isDefined;