Skip to main content

prefer-ts-extras-assert-defined

Require assertDefined from ts-extras over manual undefined-guard throw blocks.

Targeted pattern scopeโ€‹

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

Matched patternsโ€‹

  • if (value === undefined) throw ...
  • if (undefined === value) throw ...
  • if (value == undefined) throw ...
  • if (undefined == value) throw ...

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

Detection boundariesโ€‹

  • โœ… Reports direct undefined-equality guards with throw-only consequents.
  • โŒ Does not report guards that return, log, or perform additional statements.
  • โŒ Does not report typeof value === "undefined" patterns.
  • โŒ Does not auto-fix.

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

What this rule reportsโ€‹

Throw-only undefined guard blocks that can be replaced with assertDefined(value).

Why this rule existsโ€‹

assertDefined() expresses the intent of narrowing away undefined and centralizes assertion behavior.

In large services, inline guards often diverge in error types/messages. Using assertDefined gives one recognizable pattern while preserving narrowing.

โŒ Incorrectโ€‹

if (token === undefined) {
throw new Error("Token is required");
}

โœ… Correctโ€‹

assertDefined(token);

Behavior and migration notesโ€‹

  • assertDefined(value) narrows away undefined after the assertion.
  • This rule intentionally targets throw-only guards without else branches.
  • typeof value === "undefined" checks are intentionally out of scope.

Additional examplesโ€‹

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

if (undefined == monitorId) {
throw new TypeError("monitorId is required");
}

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

assertDefined(monitorId);

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

assertDefined(config.apiKey);
assertDefined(config.baseUrl);

ESLint flat config exampleโ€‹

import typefest from "eslint-plugin-typefest";

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

When not to use itโ€‹

Disable this rule if your error-handling layer requires custom throw logic in each guard block.

Package documentationโ€‹

ts-extras package documentation:

Source file: source/assert-defined.ts

/**
Assert that the given value is defined, meaning it is not `undefined`.

If the value is `undefined`, a helpful `TypeError` will be thrown.

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

const unicorn = 'unicorn';
assertDefined(unicorn);

const notUnicorn = undefined;
assertDefined(notUnicorn);
//=> TypeError: Expected a defined value, got `undefined`
```

@category Type guard
*/

Rule catalog ID: R011

Further readingโ€‹

Adoption resourcesโ€‹