Aller au contenu principal

isNil()

isNil(value): value is null | undefined

Checks if a value is null or undefined.


Parameters

value: unknown

The value to check.


Returns: value is null | undefined

true if the value is null or undefined, false otherwise.


See Also


Since

2.0.0


Example

isNil(null);      // => true
isNil(undefined); // => true
isNil(0); // => false
isNil(''); // => false
isNil(false); // => false

How it works?

Type guard that checks if a value is null or undefined.

Narrowing

Falsy vs Nil

ValueisNilvalue
null true true
undefined true true
0 false true
'' false true
false false true

Use Cases

Check for nullish values 📌

Check if a value is null or undefined. Essential for defensive programming and optional value handling.

if (isNil(value)) {
return defaultValue;
}

Early return for missing data

Guard clauses to exit early when required data is missing.

function processUser(user: User | null | undefined) {
if (isNil(user)) {
return { error: "User not found" };
}

// TypeScript knows user is User here
return { name: user.name, email: user.email };
}