Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Testing and Tooling

Formatting, Linting and Type Checking in Deno

Keep code consistent with deno fmt, catch bugs with deno lint rules and ignore comments, type-check with deno check, read docs with deno doc and wire it all into CI. No config files needed.

In most JavaScript projects you spend an afternoon choosing and configuring a formatter, a linter and a type checker before you write any real code. Deno ships all three as subcommands: deno fmt, deno lint and deno check. They work on TypeScript, JavaScript, JSX, JSON, Markdown and more, share one configuration file, and run fast because they are written in Rust.

This lesson shows what each tool does, how to tune it, how to silence it correctly when you must, and how to run everything in CI so that bad code cannot reach your main branch.

The Deno CLI is not available on this site, so commands are read-only. One runnable example builds a tiny linter in Node so you can see what a lint rule is: a function that scans code and reports patterns.

deno fmt: one style, no debates

Terminal
deno fmt              # rewrite files in place
deno fmt --check      # fail if anything is not formatted (use in CI)
deno fmt src/ main.ts # limit to paths
deno fmt --watch      # re-format on change

Before:

TypeScript
const user = {name:'Ada',
   age:36}
function greet( u ){return 'Hi '+u.name}

After deno fmt:

TypeScript
const user = { name: "Ada", age: 36 };
function greet(u) {
  return "Hi " + u.name;
}

The defaults are deliberately few: two-space indent, 80-column lines, double quotes, semicolons. You can change them in deno.json (see Configuration and Tasks):

JSON
{
  "fmt": {
    "useTabs": false,
    "lineWidth": 100,
    "indentWidth": 2,
    "semiColons": true,
    "singleQuote": false,
    "proseWrap": "preserve",
    "include": ["src/", "tests/"],
    "exclude": ["src/generated/"]
  }
}

Formatting is a safe, mechanical change: it never alters what the code does. Format on save in your editor (the Deno extension for VS Code and the LSP support this), and keep deno fmt --check as a CI gate so everyone's code looks the same and reviews focus on logic.

You can also format code embedded in Markdown files and JSON, and turn formatting off for a region:

TypeScript
// deno-fmt-ignore
const matrix = [
  1, 0, 0,
  0, 1, 0,
  0, 0, 1,
];

deno lint: find bugs and bad habits

Terminal
deno lint                # check all files
deno lint src/           # some paths
deno lint --fix          # apply safe automatic fixes
deno lint --json         # machine readable output

A lint rule is a pattern that is usually a mistake. Examples from the recommended set:

Rule Catches
no-unused-vars variables and imports that are never used
no-explicit-any the any type, which turns off type checking
no-var var instead of let / const
eqeqeq == where === was intended
require-await async functions that never await
no-undef use of a name that does not exist
no-fallthrough case blocks missing break
no-slow-types exported types JSR cannot analyze quickly (publishing, see JSR)

Output points at the exact line:

TEXT
error[no-unused-vars]: `count` is never used
 --> /app/src/main.ts:3:7
  |
3 | const count = 0;
  |       ^^^^^
  = hint: If this is intentional, prefix it with an underscore like `_count`

Found 1 problem

The hint is useful: a leading underscore (_req, _unused) marks "intentionally unused", which is why you see (_req) => in Deno handler examples.

Choosing rules

JSON
{
  "lint": {
    "include": ["src/"],
    "exclude": ["src/generated/"],
    "rules": {
      "tags": ["recommended"],
      "include": ["eqeqeq", "no-throw-literal"],
      "exclude": ["no-explicit-any"]
    }
  }
}

tags selects bundles (recommended by default; jsr and react are others). include adds individual rules, exclude removes them. List all of them with deno lint --rules.

Ignoring a rule, the right way

Sometimes the rule is wrong for one line. Ignore it narrowly and say why:

TypeScript
// deno-lint-ignore no-explicit-any -- third-party callback has no useful type
function onEvent(handler: (e: any) => void) {}
TypeScript
// deno-lint-ignore-file no-explicit-any    <- at the top: the whole file

Always name the rule. A bare ignore hides future bugs, and Deno can report ignore comments that no longer suppress anything (ban-unused-ignore).

What a lint rule looks like inside

A linter parses code into a syntax tree and walks it. To see the idea without a parser, here is a crude version that scans lines for three famous mistakes. Real linters work on the syntax tree so they are not fooled by strings or comments, but the reporting mechanics are the same.

Node.js A toy linter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

deno check: type checking

TypeScript runs directly in Deno, but by default deno run does not type-check: it strips the types and runs. This keeps startup fast. Type errors are found by:

Terminal
deno check main.ts          # check one entry point and everything it imports
deno check **/*.ts          # all files
deno run --check main.ts    # check, then run

deno test type-checks the code it runs, so a type error fails the test run. Deno enables TypeScript's strict mode by default. Example of a bug it catches:

TypeScript
function area(radius: number): number {
  return Math.PI * radius ** 2;
}

area("5");
// error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'number'.

Tune compiler options in deno.json:

JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true
  }
}

noUncheckedIndexedAccess is worth switching on: arr[0] becomes T | undefined, which forces you to handle empty arrays.

deno doc and deno info

Two more built-ins help you understand code:

Terminal
deno doc math.ts                 # print the documented public API of a module
deno doc --lint math.ts          # report exports missing JSDoc or types
deno doc --html --name="My Lib" ./mod.ts   # generate a static docs site
deno info main.ts                # dependency tree, cache locations, sizes
deno info jsr:@std/path          # inspect a remote module

JSDoc comments become documentation, and with deno test --doc the code samples inside them run as tests, so your docs cannot go stale:

TypeScript
/**
 * Adds two numbers.
 *
 * ```ts
 * import { assertEquals } from "jsr:@std/assert";
 * import { add } from "./math.ts";
 * assertEquals(add(1, 2), 3);
 * ```
 */
export function add(a: number, b: number): number {
  return a + b;
}

Put it together in CI

All the checks are non-interactive and return a non-zero exit code on problems, so a pipeline is one short script:

YAML
# .github/workflows/ci.yml
name: ci
on: [push, pull_request]
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: denoland/setup-deno@v2
        with:
          deno-version: v2.x
      - run: deno fmt --check
      - run: deno lint
      - run: deno check **/*.ts
      - run: deno test --coverage=cov/

Rather than repeating four commands in every project, wrap them in a named task, deno task ci, which the next lesson shows. Also run deno outdated now and then to see which dependencies have newer versions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command fails if any file is not formatted, without changing files?

    --check only verifies and exits with an error if formatting would change something, which is what CI needs.
  2. 2. Does deno run type-check your TypeScript by default?

    deno run skips type checking for speed. deno check, deno run --check and deno test do check types.
  3. 3. What is the best way to silence one lint warning?

    A narrow ignore comment that names the rule keeps every other check active.
  4. 4. What does a leading underscore, as in (_req) =>, tell the linter?

    no-unused-vars ignores names that start with an underscore.

Summary

  • deno fmt formats code (and JSON and Markdown); use --check in CI.
  • deno lint applies rules from tags, includes and excludes; --fix repairs what is safe; ignore narrowly with deno-lint-ignore rule.
  • deno check type-checks in strict mode; deno run alone does not.
  • deno doc and deno test --doc keep documentation accurate; deno info shows the dependency graph.
  • One CI job runs all four checks.

Next: Configuration and Tasks with deno.json