# Enable TypeScript Strict Mode in a discord.js Bot

Yes. An agent turns on strict in a discord.js bot's tsconfig, fixes each compiler error without casts to any, runs the tests and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/enable-strict-mode/discord-js/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent measures before it edits. On KevinNovak/Discord-Bot-TypeScript-Template, `tsconfig.json` sets `"strict": false` with `target` `es2021`, decorators enabled and `tests` excluded, and `package.json` builds with `tsc --project tsconfig.json` on TypeScript `^5.9.2`. With the lockfile's 5.9.2, `tsc --noEmit -p tsconfig.json` is clean, and the same command with `--strict` reports 81 errors in 27 files. The agent runs each flag alone to see what it is facing: `--strictNullChecks` accounts for 66, adding `--strictPropertyInitialization` brings that to 74, `--noImplicitAny` finds 4, `--strictBindCallApply` and `--useUnknownInCatchVariables` find one each, and the remaining strict flags find none. It writes those numbers into the pull request so a reviewer knows the size of the job before reading a line of the diff.

The errors cluster, and the agent fixes them by cause, not file by file. The largest group, 21 errors in `src/utils/client-utils.ts`, comes from helpers such as `getGuild` that declare `Promise<Guild>` and then `return;` when the id is malformed or the fetch fails with an ignored Discord error. The honest signature is `Promise<Guild | undefined>`, and widening it pushes the question to every caller, which is the point of the exercise: each call site either already checks the result or gets a check. `findButton` in `src/events/button-handler.ts` has the same shape, returning the result of `Array.find` as a plain `Button`. The eight property-initialization errors are all in `src/models/cluster-api/shards.ts` and `src/models/master-api/clusters.ts`, request models that class-transformer fills in through `src/middleware/map-class.ts`; those get a definite-assignment assertion, the one place the agent uses one, with a comment saying who assigns the field.

The small groups each have a specific fix. `src/services/logger.ts` reads `resText` after a `try` that may not have assigned it, so it is declared as `string | undefined`. `src/start-bot.ts` indexes the `Partials` enum with a string from `config.json`, which `noImplicitAny` rejects; the agent narrows the key with `keyof typeof Partials` and fails loudly on a name the enum does not have. A `catch (error)` in `src/commands/chat/dev-command.ts` uses the value as if it were typed, and gets an `instanceof` check. The rules the request sets are that no fix may introduce `any`, `@ts-ignore` or `@ts-expect-error`, and no runtime behaviour may change beyond a guard where the compiler proved a value can be absent. ESLint will not police the first rule here, because `eslint.config.mjs` turns `@typescript-eslint/no-explicit-any` off, so the agent greps its own diff for it.

Then it proves nothing moved. The vitest suite cannot even load on a fresh clone: eight of its nine files import modules that `require` the git-ignored `config/config.json`. The agent copies the three `*.example.json` files to their real names inside the sandbox, runs `npm test` before touching anything to get the baseline of 57 passing tests, and runs it again at the end along with `npm run lint`, `npm run format` and `npm run build`. It also reports one thing it leaves alone: `tsconfig.test.json`, which extends the main config to cover `tests/`, already fails type checking with strict off, on imports of builder files that do not exist and on `.ts` import extensions. `npm test` never notices because vitest does not type check, and fixing the test tree is a second pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Enable TypeScript strict mode in this discord.js bot. Read CLAUDE.md, package.json, tsconfig.json, tsconfig.test.json, eslint.config.mjs and vitest.config.ts first. Copy the *.example.json files in config/ to their real names locally (they are git-ignored; do not commit them), run npm ci, and record the baseline: npx tsc --noEmit -p tsconfig.json, the same with --strict, the error count for each strict flag on its own, and npm test. Set \"strict\": true in tsconfig.json and fix every error by cause. Widen return types that can really be absent (for example helpers in src/utils/client-utils.ts and findButton) and handle the absent case at each caller. Use a definite-assignment assertion only on class-validator model properties that class-transformer assigns, with a comment. Do not add any, @ts-ignore or @ts-expect-error, and do not change runtime behaviour except to add a guard the compiler shows is missing. Leave tsconfig.test.json's existing errors alone and list them in the pull request. Finish with npm run lint, npm run format, npm run build and npm test, and open a pull request whose description has the before and after counts and a list of every guard that changes what the bot does at runtime.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that flips one line in `tsconfig.json` and touches the files the compiler named: the `src/utils` helpers and their callers, the event handlers, the two model files, `logger.ts`, `start-bot.ts` and a handful of single-error files. The description carries the baseline table (errors per strict flag before, zero after), the test result before and after, and a short list headed "behaviour changes": each place where a new guard returns early or throws where the old code would have carried an absent value forward.

That list is what a reviewer reads first. A widened return type is safe by construction; a new early return in a handler is a decision, and the reviewer checks that skipping is right for each one, for instance that a reaction on a message whose guild cannot be fetched should be dropped and not answered with an error embed. They also scan for the definite-assignment marks and confirm each sits on a decorated model property. The diff is wide but shallow, and it conflicts easily, so the pull request is best merged soon after it opens.

## Run it on every terminal hand-off

Strict mode is the kind of job a developer starts on a quiet afternoon and abandons at error forty. Sending this body from the terminal with the repository in `resources` hands the whole count to a run in the cloud, and the developer keeps working on features in a tree the migration is not churning. Include a `request_id`, a UUID, so that a retried start returns the run already begun and does not open a second, competing branch.

When the turn ends, `GET /o/{org}/sessions/{id}` names the pull request, and the sandbox parks with its installed `node_modules` and the compiler's last output. If `main` moves while the pull request waits, a follow-up message to the same session asks it to rebase and re-run the four scripts; a second follow-up can take on the `tsconfig.test.json` errors it listed.

## Why run it on Rush?

Eighty-odd type errors are cheap one at a time and expensive together, because each fix to a return type surfaces new errors at its callers and the count goes up before it goes down. An agent in its own sandbox can run `tsc` after every group of edits for as long as that takes, and every invocation with its output is kept in the run's record. The reviewer sees the count fall across the run and can check that it fell because of guards and types, with no suppression comments.

The baseline matters as much as the result. The run records that the suite passed before the first edit and after the last one, on the same sandbox with the same copied config files, so a failing test in review cannot be blamed on the environment. Nothing in this depends on the bot's token or a live Discord connection, so the run needs only the repository.

## Frequently asked questions

### Why not enable the strict flags one at a time?

On this codebase almost all of the work is `strictNullChecks`, with a few errors from each of the others, so splitting by flag would produce one large pull request and several trivial ones. The agent still measures each flag separately and reports the numbers. On a larger bot the same request can be changed to stop after `strictNullChecks`.

### Will it sprinkle non-null assertions to make errors go away?

The request forbids that except on class-validator model properties, where a field really is assigned by class-transformer after construction. Everywhere else a value that can be `undefined` or `null` gets a wider type and a check at the caller. The pull request lists every assertion it added so they can be counted.

### Does strict mode change what the bot does?

Types alone change nothing at runtime. The guards do: where the old code passed an absent guild or channel along, the new code returns early. Each of those is listed in the pull request so a reviewer can decide whether dropping the event is the right response.

### Do the tests need my config.json?

They need a file at that path, since most modules load it with `require` when imported. The example file is enough, and the agent copies it inside its sandbox. Your real config, which holds the bot token, is ignored by git and never leaves your machine.

## More discord.js jobs

- [Fix TypeError: Cannot Read Properties of Undefined (Reading 'FLAGS') in discord.js 14](https://getrush.ai/run/fix-intents-flags-removed/discord-js/)
- [Upgrade discord.js in a TypeScript Bot](https://getrush.ai/run/upgrade-discord-js/discord-js/)
- [Write Vitest Tests for a discord.js Bot](https://getrush.ai/run/write-vitest-tests/discord-js/)

## The same job on other stacks

- [Enable mypy Strict Mode in an Existing Python Library](https://getrush.ai/run/enable-strict-mode/mypy/)
- [Turn On TypeScript Strict Mode and Fix the Errors](https://getrush.ai/run/enable-strict-mode/typescript/)

## More jobs like this: Hand off a long task

- [Turn On oxlint's Type-Aware Rules and Fix What They Flag](https://getrush.ai/run/enable-type-aware-lint-rules/oxlint/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
