# Convert a Sequelize Express App to TypeScript

Yes. An agent turns your Sequelize and Express app into typed TypeScript: model classes with inferred attributes, typed routes, tsconfig and scripts, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/convert-javascript-to-typescript/sequelize/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the app before it renames a file. In a project laid out like sequelize/express-example (the `express-main-example` directory), `package.json` depends on `sequelize` `^6.3.3`, `express` `^4.17.1`, `body-parser` and `sqlite3`, declares `engines.node` `>=10`, and has two scripts: `start` runs `node index.js` and `setup-example-db` runs `sqlite-example-database/setup.js`. `.npmrc` sets `package-lock=false`, so there is no lockfile to migrate. `sequelize/index.js` builds one `Sequelize` instance on a SQLite file with `logQueryParameters` and `benchmark` on, calls three model definers from `sequelize/models/*.model.js`, each of which calls `sequelize.define` with an explicit auto-increment `id`, then `applyExtraSetup` in `extra-setup.js` wires `orchestra.hasMany(instrument)` and `instrument.belongsTo(orchestra)`. `express/app.js` registers `bodyParser.json()` and `urlencoded`, wraps every handler in `makeHandlerAwareOfAsyncErrors`, and mounts `getAll`, `getById`, `create`, `update` and `remove` from `express/routes/{users,instruments,orchestras}.js` under `/api/<name>` by checking which functions each module exports. `express/helpers.js` exports `getIdParam`, which parses `:id` with `/^\d+$/` and throws a `TypeError` otherwise. The setup script syncs with `force: true` and seeds four users, three orchestras and ten random instruments per orchestra.

Sequelize 6 ships its own type declarations, so the conversion is mostly about the models. The agent replaces each `sequelize.define` with a class: `class User extends Model<InferAttributes<User>, InferCreationAttributes<User>>` with `declare id: CreationOptional<number>` and `declare username: string`, initialised through `User.init({...}, { sequelize, modelName: 'user' })` so the table and model names stay what the routes and the seed script expect. `Orchestra` gains `declare createInstrument: HasManyCreateAssociationMixin<Instrument, 'orchestraId'>` and `declare instruments?: NonAttribute<Instrument[]>`, which is what makes the setup script's `orchestra.createInstrument(...)` and the `include: models.instrument` query in `orchestras.js` type-check. `Instrument` declares `orchestraId` as a `ForeignKey<number>`. The `validate: { is: /^\w{3,}$/ }` rule on `username` and the `allowNull` and `unique` options move over unchanged.

The Express side is typed with `@types/express`: `getIdParam(req: Request): number`, handlers typed as `(req: Request, res: Response) => Promise<void>`, and `makeHandlerAwareOfAsyncErrors` made generic over that handler type so `app.get` and the others accept it. The route-table loop in `app.js` keeps its shape, with the `routes` object typed as a record of partial controller modules so the `if (routeController.getAll)` checks remain. `body-parser` goes, because Express 4.17 exposes `express.json()` and `express.urlencoded()` itself, which removes a dependency rather than typing it. `pickRandom` and `randomDate` in `sqlite-example-database/helpers` get generic and `Date` signatures.

The agent adds `typescript`, `tsx`, `@types/express` and `@types/node` as dev dependencies, a `tsconfig.json` with `strict`, `module` and `moduleResolution` set for Node, `outDir` `dist` and `include` covering `express`, `sequelize`, `sqlite-example-database` and `index.ts`, and changes the scripts: `start` runs the compiled `dist/index.js` after a `build` of `tsc`, `dev` runs `tsx index.ts`, and `setup-example-db` runs `tsx sqlite-example-database/setup.ts`. `engines.node` moves up to a current LTS, because Node 10 cannot run any of this. It then runs `tsc --noEmit` until there is no error, `npm run setup-example-db` to recreate the SQLite file, starts the server and requests `/api/users`, `/api/orchestras?includeInstruments` and `/api/users/abc` (which must still answer with the `TypeError` path) to show the behaviour is unchanged.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Convert this Sequelize and Express app from JavaScript to TypeScript. Read package.json, .npmrc, index.js, express/app.js, express/helpers.js, every file under express/routes and sequelize, and sqlite-example-database/setup.js first. Replace each sequelize.define with a Model subclass using InferAttributes, InferCreationAttributes and CreationOptional, keep the model names, validations and the hasMany/belongsTo association, and declare the association mixins the setup script and the orchestras route use. Type the Express handlers and the async-error wrapper with @types/express, replace body-parser with express.json and express.urlencoded, add typescript, tsx, @types/express and @types/node as dev dependencies, a strict tsconfig.json, and build, start, dev and setup-example-db scripts. Raise engines.node to a current LTS. Run tsc --noEmit until it is clean, recreate the example database, start the server and request /api/users, /api/orchestras?includeInstruments and /api/users/abc, and open a pull request that quotes the type-check and those responses.",
  "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

The pull request renames every `.js` file under `express/`, `sequelize/` and `sqlite-example-database/` to `.ts`, adds `tsconfig.json`, changes `package.json` (four dev dependencies, one dependency removed, four scripts, `engines`) and adds `dist` to `.gitignore` beside `node_modules` and `*.sqlite`. Its description shows the three model classes, quotes a clean `tsc --noEmit`, and pastes the JSON answers from the three requests so the reviewer can compare them with the JavaScript app's.

A reviewer reads the models first, because that is where a wrong `declare` would silently widen a type, then the handler signatures, then the scripts. The reviewer checks that `modelName` matches what the seed script and the routes use (`user`, `instrument`, `orchestra`), that `orchestraId` is still created by the association rather than redeclared, and that `npm run build` followed by `npm start` works without `tsx`.

After the merge, a new model is a class with declared attributes, and a route that reads a field the model does not have fails at compile time instead of returning an empty column at runtime.

## Run it on every service still written in JavaScript

A team moving its Node services to TypeScript one at a time sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own code: a service with migrations under `sequelize-cli` keeps them in JavaScript and gets a note in the pull request, and one that already has a lockfile gets it updated.

An automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a .js file to a package that has a tsconfig.json, convert the file and post a review with the typed version" runs once per pull request. The trigger adds the pull request after the prompt and fills in nothing else. Only work by an owner, member or collaborator fires it.

## Why run it on Rush?

A conversion like this is a long chain of small decisions, and the one that matters most, how each model is typed, is easy to get subtly wrong in a way `tsc` accepts and the app only reveals when a query returns the wrong shape. The agent types the models against Sequelize's own helpers, then runs the real server against the real seed data in its own sandbox and compares the answers, and keeps every command and response with the pull request.

A reviewer reads three classes and three JSON responses instead of re-running the app. A team with several services starts the same request across all of them at once and merges them one by one.

## Frequently asked questions

### Will the models behave the same?

Yes. `Model.init` with the same attributes, `modelName` and options produces the same table, columns and validations as `sequelize.define`, and the `hasMany`/`belongsTo` calls stay in `extra-setup.ts`. The agent proves it by recreating the SQLite file and comparing the API responses.

### Do I have to compile before running?

`npm start` runs the compiled output in `dist/`, which is what a production process should run. `npm run dev` runs the sources directly with `tsx` for local work. The pull request leaves both and says which to use where.

### What about CommonJS versus ES modules?

The app uses `require` everywhere, so the agent targets CommonJS output and writes `import` syntax in the sources, which `tsc` compiles down. Switching to ESM output is possible later and is a separate change the pull request names.

### Why remove body-parser?

Express 4.17 includes `express.json()` and `express.urlencoded()`, which are the same parsers. Dropping the package is one fewer dependency to type and update, and the request handling is unchanged.

## More Sequelize jobs

- [Fix "TypeError: sequelize.import is not a function" after upgrading to Sequelize 6](https://getrush.ai/run/fix-sequelize-import-is-not-a-function/sequelize/)
- [Migrate a Sequelize App From SQLite to Postgres](https://getrush.ai/run/migrate-sqlite-to-postgres/sequelize/)
- [Write Integration Tests for a Sequelize and Express API](https://getrush.ai/run/write-integration-tests/sequelize/)

## The same job on other stacks

- [Convert a Bolt for JavaScript Slack App to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/slack-bolt/)
- [Convert a Socket.IO Chat Server to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/socket-io/)
- [Convert a SolidJS App From JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/solidjs/)

## 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/)
