Linting with typescript-eslint

Intermediate · 11 min

Set up typescript-eslint with flat config and typed linting, and catch the async and any-related bugs that tsc lets through.

Before thisTyping asynchronous codetsconfig explained

Checkly · 11 min

Linting with typescript-eslint

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ChecklyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The type checker answers "is this program type-correct?" A linter answers "is this code likely to be a mistake?" Plenty of bugs are perfectly well typed, so the two tools catch different things and you want both.
  • typescript-eslint is two pieces: a parser that lets ESLint read TypeScript syntax, and a plugin of rules. Current setups use ESLint's flat config, an `eslint.config.mjs` file that exports an array of config objects.
  • Typed linting gives rules access to the type checker. You turn it on with a `*TypeChecked` preset plus `parserOptions.projectService: true`, which tells the parser to find the right `tsconfig.json` for each file the same way your editor does.
  • `no-floating-promises` and `no-misused-promises` catch promises nobody awaits or handles, which compile cleanly but silently drop errors and break ordering.
  • The `no-unsafe-*` rules track values typed `any` as they flow into assignments, member accesses, calls, and returns, closing the hole `any` punches through strict mode.

Bugs that type-check

Here is a function that compiles under strict with zero errors:

async function saveUser(id: string): Promise<void> {
  await fetchUser(id);
}

function onSubmit(id: string) {
  saveUser(id); // no-floating-promises: nothing awaits or catches this
}

const ids = ["a", "b"];
ids.forEach(async (id) => {
  // no-misused-promises: forEach ignores the returned promise
  await saveUser(id);
});

const raw = JSON.parse(text);           // no-unsafe-assignment
const userName: string = raw.user.name; // no-unsafe-member-access

Every line is type-correct. Calling a function and ignoring its result is legal. An async function is assignable to a callback that returns void. JSON.parse returns any, and any is allowed to go anywhere. Yet each line is a likely bug: a rejected save vanishes, the forEach finishes before any user is saved, and raw.user.name can crash on data you never checked.

The compiler’s question is “do these types fit together?” A linter asks a different one: “does this code look like a mistake?” That’s the gap typescript-eslint fills. General linting and formatting setup is covered in frontend’s linting lesson. This lesson is about what changes when the code is TypeScript.

The setup: flat config

typescript-eslint ships as one package, typescript-eslint, that bundles a parser (so ESLint can read type annotations at all) and a plugin full of TypeScript-aware rules. Modern ESLint reads a flat config: an eslint.config.mjs that exports an array of config objects, applied in order.

// eslint.config.mjs
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";

export default tseslint.config(
  eslint.configs.recommended,
  tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
      },
    },
  },
  {
    files: ["**/*.js", "**/*.mjs"],
    extends: [tseslint.configs.disableTypeChecked],
  },
);

Install with npm install --save-dev eslint @eslint/js typescript-eslint, then run npx eslint ..

Reading it top to bottom: ESLint’s own recommended rules, then typescript-eslint’s recommended rules including the type-aware ones, then the switch that gives those rules type information, then an override that turns type-aware rules off for plain JavaScript config files that no tsconfig covers. tseslint.config(...) is a small helper that adds type hints and supports extends inside an object. Recent ESLint versions also export defineConfig from eslint/config, which does the same job, and the typescript-eslint docs now show that form. Either one produces the same array.

The presets come in layers. recommended is the safe baseline. strict adds more opinionated rules. stylistic covers consistency rather than correctness. Each has a TypeChecked twin that adds the rules needing type information.

What typed linting adds

Without type information, a lint rule only sees syntax: saveUser(id) is a call expression and nothing more. It can’t know saveUser returns a promise. projectService: true fixes that. For each file, the parser asks TypeScript’s project service (the same machinery your editor’s language server uses) to find the tsconfig.json that includes it, then builds a program the rules can query. tsconfigRootDir anchors relative paths so the result doesn’t depend on which directory you ran ESLint from. Older guides set parserOptions.project: "./tsconfig.json" instead. That still works, but you have to list every tsconfig yourself.

With types available, the rules from the opening example become possible:

  • no-floating-promises reports a promise-valued expression whose result is dropped. Fix it with await, a .catch(), return, or an explicit void saveUser(id) when firing and forgetting is truly what you mean.
  • no-misused-promises reports promises passed where something else is expected, most often an async function handed to a callback typed () => void such as forEach or a DOM event listener. (tsc itself already rejects the bluntest case, if (isAdmin(id)) on a promise.)
  • no-unsafe-assignment, no-unsafe-member-access, no-unsafe-call, no-unsafe-argument, no-unsafe-return follow an any value and complain wherever it spreads into typed code. The fix is to give the value a real type, usually unknown plus narrowing or a schema check.

The asynchronous half connects straight to typing asynchronous code: the types tell you a function returns a promise, and these rules make sure somebody deals with it.

Living with it

Typed linting costs time. Each run builds a TypeScript program, so expect it to take roughly as long as tsc --noEmit on the same files. Run it in the editor and in CI. Many teams leave it out of pre-commit hooks so commits stay fast.

On an existing codebase, recommendedTypeChecked will probably report hundreds of no-unsafe-* hits on day one. Turning those rules to "warn" in a later config object, and promoting them back to errors once the count falls, is a reasonable path. Disabling a rule on one line with // eslint-disable-next-line @typescript-eslint/no-floating-promises should come with a comment saying why.

What the video covers

Checkly’s walkthrough adds type checking and typescript-eslint to a Playwright test suite, using a flat eslint.config.mjs and the tseslint helpers, then turns on typed linting so no-floating-promises can flag promises the tests never await. Test code is a good place to see why this matters: a forgotten await can let a test finish before its assertions run. Nothing about the setup is specific to Playwright, and the config above is the same pattern for any TypeScript project. Josh Goldberg’s talk in the links is the best explanation of why typed lint rules exist, from the project’s maintainer, but its config examples use the older .eslintrc format. Keep the rule ideas and use the flat config shown here.

Check yourself

  1. 01Why doesn't `tsc` report `saveUser(id);` as an error when `saveUser` returns a `Promise`?

    Calling a function and ignoring its return value is legal and type-correct. The compiler has no rule that a returned promise must be used. Whether that is a bug is a judgment about intent, which is the linter's job, and `no-floating-promises` is the rule that makes it.

  2. 02What does `parserOptions.projectService: true` do in a typescript-eslint config?

    It makes the parser use TypeScript's project service, the same machinery editors use, to find the `tsconfig.json` that owns each linted file and build type information from it. That type information is what the type-aware rules query.

  3. 03Why is passing an `async` callback to `array.forEach` flagged by `no-misused-promises`?

    `forEach` expects a callback that returns `void` and throws away whatever comes back. An async callback returns a promise, so nothing waits for the work to finish and a rejection is never handled, even though the types are compatible.

  4. 04What is the cost of typed linting, and how do you limit it?

    Each lint run has to build a TypeScript program, so it is slower than syntax-only linting, close to the cost of a type check. You keep it to files your tsconfig covers and switch type-aware rules off for plain config scripts with `tseslint.configs.disableTypeChecked`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark