Sub topic 8
Catching real bugs with type-checked rules
This chapter assumes you have the type-aware setup from the previous chapter working: recommendedTypeChecked (or strictTypeChecked) in eslint.config.mjs, with projectService: true. It also assumes you can read basic Promise and async/await code. Here you will see which type-checked rules find bugs that syntax-only rules miss, how to fix what they report, and how to handle the errors that come with them.
Why type information finds bugs
A syntax-only rule sees code as a tree of nodes. It can tell that save('a'); is a call statement. It cannot tell whether save returns a Promise, because that fact lives in a declaration that may be in another file.
Type-checked rules ask the TypeScript compiler for that fact. The rule receives a node, asks the type checker what the node's type is, and reports only if the type matches a known hazard.
Three consequences follow from this:
- Each rule is only as accurate as your types. A value typed
anygives the checker nothing to work with. - The file must belong to a TypeScript project, or the parser cannot build types for it.
- Compiler settings matter. Several rules assume
strict: truein yourtsconfig.json.
The rules that earn their cost
All rules in this table are in recommendedTypeChecked unless noted.
| Rule | Bug it catches |
|---|---|
| `no-floating-promises` | A Promise that is neither awaited nor handled, so rejections vanish |
| `no-misused-promises` | A Promise used where a boolean or a void-returning callback is expected |
| `await-thenable` | `await` on a value that is not a Promise |
| `no-unsafe-assignment`, `no-unsafe-member-access`, `no-unsafe-call`, `no-unsafe-return`, `no-unsafe-argument` | `any` leaking through your code and switching off type checking |
| `restrict-template-expressions` | Template strings that print `[object Object]` or `undefined` |
| `only-throw-error` | Throwing values that are not `Error` objects, which lose stack traces |
| `no-unnecessary-condition` | Checks that can never be true or false (`strictTypeChecked` only) |
| `switch-exhaustiveness-check` | A `switch` that forgets a union member (not in any preset) |
Floating promises
This is the rule most teams adopt first. A call to an async function without await runs, but a failure goes unnoticed or becomes an unhandled rejection.
async function save(id: string): Promise<void> {
// persist the record
}
export function run(): void {
save('a'); // @typescript-eslint/no-floating-promises reports this call
}
export async function runFixed(): Promise<void> {
await save('a');
}There are three accepted fixes, and the right one depends on intent:
awaitthe call, when the caller should wait for the result or see the error.- Attach a handler with
.catch(...)or.then(onOk, onError), when you deliberately do not wait. - Prefix with
void(void save('a');), when you want to mark the call as intentionally unobserved. The rule allows this by default viaignoreVoid. Use it sparingly, because a rejection is still unhandled.
Misused promises
no-misused-promises reports a Promise where TypeScript's types would otherwise let it slide through. The common case is an async callback passed to a function that expects a callback returning void.
async function save(id: string): Promise<void> {
// persist the record
}
export function saveAll(ids: string[]): void {
// no-misused-promises: forEach expects a callback that returns void
ids.forEach(async (id) => {
await save(id);
});
}
export async function saveAllFixed(ids: string[]): Promise<void> {
await Promise.all(ids.map((id) => save(id)));
}The first version returns before any save finishes. A failed save becomes an unhandled rejection, and the caller cannot wait for completion. The fixed version collects the Promises with map and waits for all of them.
The rule also reports Promises used in conditions, such as if (isReady()) where isReady is async. A Promise object is always truthy, so that branch always runs.
Awaiting a non-Promise
await-thenable reports await on a value that has no then method. The await is harmless at runtime, but it usually means someone changed a function from async to sync, or that a call is missing a promise-returning step.
export function total(prices: number[]): number {
return prices.reduce((sum, price) => sum + price, 0);
}
export async function report(): Promise<number> {
return await total([1, 2, 3]); // await-thenable: total is not async
}Stopping `any` from spreading
JSON.parse, fetch(...).then(r => r.json()), and untyped libraries return any. The no-unsafe-* rules report each place where an any value flows into a typed variable, is accessed, is called, or is returned. The goal is to make you validate data once, at the boundary.
interface Settings {
theme: 'light' | 'dark';
retries: number;
}
export function loadUnsafe(text: string): Settings {
const data = JSON.parse(text); // no-unsafe-assignment
return data; // no-unsafe-return
}
function isSettings(value: unknown): value is Settings {
return (
typeof value === 'object' &&
value !== null &&
'theme' in value &&
(value.theme === 'light' || value.theme === 'dark') &&
'retries' in value &&
typeof value.retries === 'number'
);
}
export function loadSettings(text: string): Settings {
const data: unknown = JSON.parse(text);
if (!isSettings(data)) {
throw new Error('Invalid settings');
}
return data;
}Assigning any to unknown is allowed. From there, a type guard narrows the value, and the rest of the code sees a real Settings. A schema library such as Zod does the same job with less hand-written code.
Text output and thrown values
restrict-template-expressions reports values whose string form is not useful. Putting an object in a template prints [object Object], and undefined prints the word "undefined". Interpolate the specific property instead:
const user = { id: 1, name: 'Ada' };
console.log(`user: ${user.name} (#${user.id})`);only-throw-error reports throw 'failed' or throw { code: 1 }. Those values carry no stack trace, and catch blocks that read error.message fail on them.
Opting in to rules outside the preset
switch-exhaustiveness-check is valuable when you model state with a union, because it turns a forgotten case into a lint error. Add it in a TypeScript-scoped entry after the preset:
// additional entry in the flat config array
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/switch-exhaustiveness-check': 'error',
},
},With this rule on, adding 'failed' to the union below makes every switch that omits it fail lint:
type Status = 'idle' | 'loading' | 'failed';
export function describe(status: Status): void {
switch (status) {
case 'idle':
console.log('Idle');
break;
case 'loading':
console.log('Loading');
break;
// switch-exhaustiveness-check: 'failed' is not handled
}
}Fix it by adding a case 'failed': branch. Do not add a default that silently swallows new members, because the rule treats that as a way to hide the gap (by default it still requires listing the cases).
Common problems
- "Parsing error: ... was not found by the project service." The file is not covered by any
tsconfig.json. Add it toinclude, or if it is a plain JavaScript file, scopetseslint.configs.disableTypeCheckedto it, as shown in the earlier chapter on file-scoped settings. - A flood of
no-unsafe-*reports after enabling the preset. Your codebase has manyanyvalues, often from untyped dependencies. Fix the highest-traffic boundaries first (parsing, HTTP clients), or temporarily set theno-unsafe-*rules to'warn'while you reduce them. - Rules that never report. If
strict(specificallystrictNullChecks) is off in the tsconfig that lint reads,no-unnecessary-conditionhas little to work with and gives misleading results. - Reports that disagree with the editor's red squiggles. Lint reads the tsconfig that the project service finds for each file. A test file may fall under a different tsconfig than you expect.
Triage workflow
When you first enable type-checked rules on an existing codebase, work in this order:
- Run
npx eslint .and group the results by rule. - Fix
no-floating-promises,no-misused-promisesandawait-thenablefirst. These are almost always real defects. - Address
no-unsafe-*at data boundaries. Each fix there removes many downstream reports. - Treat style-flavoured results as lower priority, and suppress with a documented reason only when a fix is not possible.
Exercise
This function is flagged by @typescript-eslint/no-misused-promises. Explain why it is a bug, and rewrite it so the caller can wait for every upload to finish.
async function upload(file: string): Promise<void> {}
export function uploadAll(files: string[]): void {
files.forEach(async (file) => {
await upload(file);
});
}
Show answer
forEach ignores the Promise each callback returns. uploadAll returns immediately, the caller cannot know when uploads finish, and any failure becomes an unhandled rejection. Fixed version:
export async function uploadAll(files: string[]): Promise<void> {
await Promise.all(files.map((file) => upload(file)));
}
Exercise
const data = JSON.parse(text); triggers no-unsafe-assignment. What type should you give data, and what must you do before using it as a Settings object?
Show answer
Declare it as unknown (const data: unknown = JSON.parse(text);). Then narrow it with a type guard or a schema validator, and only use it as Settings after the check passes.