Skip to main content

prefer-ts-extras-assert-present

Require assertPresent from ts-extras over manual == null throw guards.

Targeted pattern scopeโ€‹

This rule focuses on throw-only nullish guards that map directly to assertPresent(value).

Matched patternsโ€‹

  • if (value == null) { throw ... }
  • if (value === null || value === undefined) { throw ... }
  • if (value === undefined || value === null) { throw ... }

Only if statements that have no else branch and a throw-only consequent are reported.

Detection boundariesโ€‹

  • โœ… Reports nullish guards written as == null or explicit null/undefined OR checks.
  • โŒ Does not report a null-only guard (value === null) or undefined-only guard.
  • โŒ Does not report branches that do more than throw.
  • โŒ Does not auto-fix.

These boundaries keep matching deterministic and avoid broad semantic overreach during migration.

What this rule reportsโ€‹

Throw-only nullish guard blocks that can be replaced with assertPresent(value).

Why this rule existsโ€‹

assertPresent() communicates nullish-assertion intent and provides a reusable narrowing helper.

This is a high-signal utility for request handlers and parsing layers where nullable inputs are common.

โŒ Incorrectโ€‹

if (payload == null) {
throw new Error("Missing payload");
}

โœ… Correctโ€‹

assertPresent(payload);

Behavior and migration notesโ€‹

  • assertPresent(value) narrows value to NonNullable<T>.
  • The rule covers nullish guards (== null or explicit null || undefined) with throw-only consequents.
  • Null-only or undefined-only assertions are intentionally left untouched.

Additional examplesโ€‹

โŒ Incorrect โ€” Additional exampleโ€‹

if (input === null || input === undefined) {
throw new TypeError("input is required");
}

โœ… Correct โ€” Additional exampleโ€‹

assertPresent(input);

โœ… Correct โ€” Repository-wide usageโ€‹

assertPresent(currentUser);
assertPresent(sessionId);

ESLint flat config exampleโ€‹

import typefest from "eslint-plugin-typefest";

export default [
{
plugins: { typefest },
rules: {
"typefest/prefer-ts-extras-assert-present": "error",
},
},
];

When not to use itโ€‹

Disable this rule if your domain code requires custom error payloads inline at each nullish guard.

Package documentationโ€‹

ts-extras package documentation:

Source file: source/assert-present.ts

/**
Assert that the given value is present (non-nullable), meaning it is neither `null` nor `undefined`.

If the value is not present (`undefined` or `null`), a helpful `TypeError` will be thrown.

@example
```
import {assertPresent} from 'ts-extras';

const unicorn = 'unicorn';
assertPresent(unicorn);

const notUnicorn = null;
assertPresent(notUnicorn);
//=> TypeError: Expected a present value, got `null`
```

@category Type guard
*/

Rule catalog ID: R013

Further readingโ€‹

Adoption resourcesโ€‹