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 Errorguards 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 toError.- This rule only targets throw-only negative guards with no
elsebranch. - 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.
*
* @category Type guard
*
* @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;
* }
* ```
*/
Rule catalog ID: R012