isDefined
The isDefined utility is a type guard that checks if a value is NOT undefined or null. It is essential for safely handling optional values and cleaning up data sets.
Implementation
View Source Code
ts
/**
* Checks if a value is defined (not `undefined`).
*
* @example
* ```ts
* isDefined(123); // true
* isDefined(undefined); // false
* isDefined('hello world'); // true
* isDefined({}); // true
* isDefined([]); // true
* isDefined(null); // true
* ```
*
* @param arg - The value to check.
*
* @returns `true` if the value is defined, else `false`.
*/
export function isDefined<T>(arg: T | undefined): arg is T {
return arg !== undefined;
}Features
- Isomorphic: Works in both Browser and Node.js.
- Type Guard: Automatically narrows types to exclude
nullandundefined. - Durable: Unlike a simple truthiness check, it correctly identifies
0,false, and''as defined values.
API
ts
function isDefined<T>(value: T): value is NonNullable<T>;Parameters
value: The value to check.
Returns
trueif the value is neithernullnorundefined; otherwise,false.
Examples
Basic Usage
ts
import { isDefined } from '@vielzeug/toolkit';
isDefined('hello'); // true
isDefined(0); // true
isDefined(false); // true
isDefined(null); // false
isDefined(undefined); // falseFiltering Arrays
ts
import { isDefined, filter } from '@vielzeug/toolkit';
const data = ['a', undefined, 'b', null, 'c'];
// TypeScript correctly infers the result as string[]
const cleanData = filter(data, isDefined);
// ['a', 'b', 'c']Implementation Notes
- Returns
trueifvalue !== undefined && value !== null. - Throws nothing; safe for any input type.