Skip to main content

prefer-ts-extras-assert-error

Require assertError from ts-extras over manual instanceof Error throw guards.

Targeted pattern scopeโ€‹

This rule focuses on throw-only negative instanceof Error guards that map directly to assertError(value).

Matched patternsโ€‹

  • if (!(value instanceof Error)) { throw ... }

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

Detection boundariesโ€‹

  • โœ… Reports negative instanceof Error guards wrapped in !().
  • โŒ Does not report positive-form patterns like if (value instanceof Error) { ... } else { throw ... }.
  • โŒ Does not report checks against custom error classes in this rule.
  • โŒ Does not auto-fix.

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

What this rule reportsโ€‹

Throw-only negative instanceof Error guards that can be replaced with assertError(value).

Why this rule existsโ€‹

assertError() communicates intent directly: "this value must be an Error". That reduces repetitive custom guard code in catch pipelines.

โŒ Incorrectโ€‹

if (!(error instanceof Error)) {
throw new TypeError("Expected Error");
}

โœ… Correctโ€‹

assertError(error);

Behavior and migration notesโ€‹

  • assertError(value) narrows unknown caught values to Error.
  • This rule only targets throw-only negative guards with no else branch.
  • Positive-form or custom-error-class guards are intentionally out of scope.

Additional examplesโ€‹

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

if (!(reason instanceof Error)) {
throw new TypeError("Expected Error instance");
}

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

assertError(reason);

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

assertError(caughtValue);
assertError(lastFailureReason);

ESLint flat config exampleโ€‹

import typefest from "eslint-plugin-typefest";

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

When not to use itโ€‹

Disable this rule if your project intentionally avoids runtime helper dependencies or enforces a different assertion utility layer.

Package documentationโ€‹

ts-extras package documentation:

Source file: source/assert-error.ts

/**
Assert that the given value is an `Error`.

If the value is not an `Error`, a helpful `TypeError` will be thrown.

This can be useful as any value could potentially be thrown, but in practice, it's always an `Error`. However, because of this, TypeScript makes the caught error in a try/catch statement `unknown`, which is inconvenient to deal with.

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

try {
fetchUnicorns();
} catch (error: unknown) {
assertError(error);

// `error` is now of type `Error`

if (error.message === 'Failed to fetch') {
retry();
return;
}

throw error;
}
```

@category Type guard
*/

Rule catalog ID: R012

Further readingโ€‹

Adoption resourcesโ€‹