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 awayundefinedafter the assertion.- This rule intentionally targets throw-only guards without
elsebranches. 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