is-not-null-or-undefined
Version:
A TypeScript utility function to check if a value is not null or undefined
55 lines (38 loc) • 1.1 kB
Markdown
if a value is not `null` or `undefined`.
```bash
npm install is-not-null-or-undefined
```
```bash
yarn add is-not-null-or-undefined
```
```bash
pnpm add is-not-null-or-undefined
```
```typescript
import { isNotNullOrUndefined } from 'is-not-null-or-undefined';
// Returns true for non-`null` and non-`undefined` values
isNotNullOrUndefined('string'); // true
isNotNullOrUndefined(123); // true
isNotNullOrUndefined({}); // true
isNotNullOrUndefined([]); // true
isNotNullOrUndefined(false); // true
isNotNullOrUndefined(0); // true
// Returns false for `null` and `undefined` values
isNotNullOrUndefined(null); // false
isNotNullOrUndefined(undefined); // false
```
The function acts as a TypeScript type guard, narrowing the type from `T | null | undefined` to `T`:
```typescript
const value: string | null | undefined = getValue();
if (isNotNullOrUndefined(value)) {
// value is now typed as string
console.log(value.toUpperCase());
}
```
A TypeScript utility function & type-guard to check