A deep dive into tsrs

By

Updated

Tagged: TypeScript

Understand tsrs, the Rust port of TypeScript. Try the compiler, compare benchmarks, explore its architecture, and build a browser-based type checker.

tsrs is an experimental Rust port of the TypeScript compiler. It type-checks your code, emits JavaScript and declaration files, and even ships a WebAssembly build you can run inside a browser.

Cloudflare and VoidZero announced it on October 20, 2026. They’re working alongside Max Schwenk from Owner.com, who created the port, and collaborating with the TypeScript team as the project joins the Oxc toolchain.

The headline numbers are up to 8× faster checking and roughly 70% less memory than TypeScript 7.0 at equal checker counts. Those come from early vendor benchmarks, so real results will depend on the workload.

In this post we’ll look at which parts of TypeScript tsrs replaces, why anyone would port a compiler Microsoft already ported to Go, and what running it in a browser involves. Then we’ll run the native compiler and build a small browser editor that reports real TypeScript errors locally. The examples here are small, while the large-project numbers come from the project’s own measurements.

The language, compiler, and runtime

When you work with TypeScript, three separate pieces are doing the job, and it’s easy to lump them together.

The language defines what your program means: type annotations, generics, type inference, and which assignments are allowed. The compiler enforces those rules by loading files, resolving imports, checking types, and optionally producing JavaScript. The runtime executes that JavaScript, whether that’s a browser’s JavaScript engine, Node.js, or Bun.

Take this tiny example:

function greet(name: string) {
  return `Hello, ${name}`
}

console.log(greet('Flavio'))

The compiler reads name: string to check calls to greet. By the time the code reaches the JavaScript runtime, that annotation is gone.

Implementing the compiler in Rust leaves your .ts files unchanged. It speeds up your feedback loop while you develop and build, while your app’s runtime speed stays a separate measurement because the JavaScript you run is the same.

Tool or stageIts jobWhat you get
Type checkerCheck whether types agreeErrors, or a clean pass
TypeScript emitTransform TypeScript into JavaScriptJavaScript, plus optional declarations and source maps
BundlerResolve and package an application’s modulesFiles ready to deploy
JavaScript runtimeExecute the programYour running app

Plenty of tools handle more than one row in that table, so keep these roles separate when comparing them. A tool that strips annotations quickly can still leave type checking to another command.

If you want to go deeper on the language itself, check out my TypeScript Guide. For the runtime side, I covered that in what happens when Bun runs a TypeScript file.

Where tsrs comes from

Microsoft already moved the TypeScript compiler from TypeScript to Go, and tsrs builds straight from that native Go codebase.

tsrs is a function-by-function port of the Go implementation, using upstream TypeScript as its reference (the full breakdown is in the compatibility document). TypeScript’s maintainers still decide how the language works, and the tsrs team follows those decisions and reproduces them in Rust.

Even tiny differences can break things. Say a dependency uses a complex conditional type. If one compiler accepts it and the other rejects it, you’ve got a compiler compatibility problem before you touch a line of your own code.

Error output matters just as much. Editors read those locations to underline code, build tools inspect exit statuses, and tests often compare diagnostics or generated declaration files. The tsrs team treats any difference in diagnostics, message text, or exit codes as a bug, even if an alternative message might look nicer on its own.

The repository tracks upstream development and aims for a stable release against TypeScript 7.1 with full conformance. Because the current package is experimental, run it alongside your existing type check for now instead of swapping it in as a replacement.

Follow a file through the compiler

A TypeScript compiler does a lot more than strip : string from a function parameter.

It starts with your project configuration. Settings like include, exclude, and files tell it which root files to load, and imports pull in the rest of the program, including declaration files from installed packages.

Parsing then turns the source text into a structured representation. A function declaration becomes something the compiler can inspect: its name, parameters, body, and the expressions inside it.

Binding links names to declarations, so when the checker hits a call to greet, it knows which function declaration that name refers to. Checking then compares the argument against the parameter. On greet(42), it catches a number where the function expects a string.

Fig 1 · 1/4What the compiler does with your code
Read the configured project

The illustration above walks through that same snippet across scenes: the source code, the relationships the compiler tracks, the type error, and the possible outputs. Each scene adds another layer to the example.

If emit is enabled, the compiler transforms the source and writes the output files. That can include JavaScript, declaration files describing your exported types, and source maps tying the generated code back to the original source.

With --noEmit, you tell the compiler to check types without writing JavaScript or declaration files. That’s what you want when Vite or a framework already handles your build.

Watch out for one small detail with incremental builds: --noEmit can still write a .tsbuildinfo cache when incremental checking is enabled. You can see how those options interact in the emit documentation.

Why Rust could help

Writing the compiler in Rust gives the team different ways to lay out memory and split work across threads. The tsrs repository goes well beyond a literal Go-to-Rust translation, adding changes to memory layout, checker caches, and how checking work is divided between threads.

Keeping compiler data compact

A large codebase creates a huge number of compiler objects: syntax nodes for the source, symbols for declarations, and types generated while resolving expressions and generics.

Those objects point to each other constantly, and across a big graph the size of all those references adds up.

On supported platforms, tsrs stores compact handles into an arena, which is a region of memory used to allocate a group of related objects (described in the pointer-compression notes). Think of a compact handle as an object’s position inside that region. Smaller handles shrink any structure packed with references.

Turning a handle back into a real address takes extra work on access, so the tradeoff comes down to memory saved versus access cost. The team’s notes track those measurements directly.

Releasing data when it is no longer needed

Take a test file that imports your application code while nothing else imports the test file. Once the compiler finishes checking it, it can free that file’s syntax data if nothing else needs it.

The leaf-file memory notes explain which files and checking modes qualify. Freeing a file right after checking it isn’t automatic, because declaration merging, imports, and shared compiler state can keep its data reachable. The compiler has to prove later work won’t need that data before releasing it.

Building an optimized compiler binary

Release builds also use profile-guided optimization. The build runs representative workloads, records which code paths execute, and feeds that profile into compiling the final binary.

That’s why a development build you compile from source can perform differently from a published benchmark binary.

All of these choices have their own costs and platform constraints, which you can follow in the Rust engineering guide. When you evaluate tsrs, trust benchmarks on real projects over the fact that it’s written in Rust.

Reading the benchmark charts

Compiler benchmarks move around a lot depending on the codebase, the compiler revision, and how many checker threads you give them.

Cloudflare says it worked with the TypeScript team to line up the configurations in its announcement, and that the newer TypeScript beta already includes some improvements contributed upstream from tsrs.

The repository also keeps a separate historical benchmark report. The chart below pulls three workloads from that report, comparing TypeScript 7.0 with a tsrs build tracking later TypeScript development, so treat these numbers separately from the announcement headline.

Fig 2 · 1/4How checker settings change the comparison
Equal checker counts · time

The first scenes lock both compilers to 4 checkers. The later scenes switch to each compiler’s defaults on that machine, which means 4 checkers for the Go compiler and 16 for tsrs, so you can compare both elapsed time and peak memory side by side.

Both axes start at zero, lower is better, and the scale stays fixed for each metric as you flip between configurations.

These are native CLI runs (separate from the browser build) on a Linux box with 16 vCPUs and 63 GB of RAM. Each timing is the median of 10 interleaved runs for tsrs and 3 for the Go compiler.

Equal threads and default settings answer different questions

Locking both compilers to the same checker count tells you how they perform per worker.

Running with defaults tells you what you’ll get out of the box without touching any flags. When tsrs grabs 16 cores instead of 4, that extra concurrency is part of the default experience, and it shows up in resource usage too.

You can spot that tradeoff in the memory numbers right away. Giving tsrs more checkers cuts elapsed time, while pushing peak memory higher than its 4-checker run.

The benchmark methodology walks through how the workloads were set up and measured. Before you quote any compiler benchmark, check these details:

SettingWhy it matters
Checker threadsDefaults can give each compiler a different thread count
TypeScript revisionA language change can report different errors on the same code
Incremental cacheA warm check does far less work than a cold check
Files and configurationSkipping files can make a compiler look faster than it is
Generated dependenciesMissing declarations can bail out before the real workload runs
DiagnosticsA fast run still has to catch the right errors
Build configurationRelease binaries and development builds perform very differently

Compare the errors too

In those three workloads, the historical report traces diagnostic differences to upstream TypeScript changes and cross-checks them against the matching TypeScript dev build. It also flags a real tsrs bug in a 16-checker Drizzle ORM run where the error count matched, while the error locations did not.

Running both compilers on the same repository only tells half the story if they target different TypeScript revisions. A Rust port tracking upcoming TypeScript changes can legitimately disagree with today’s stable release.

Treat matching error counts as a rough sanity check, since two compilers can both report five errors for completely different reasons or on different lines. Whenever numbers or outputs diverge, diff the full diagnostics.

A speedup ratio needs a baseline

Dropping a type check from 20 seconds to 5 seconds is a 4x speedup, and you get 15 seconds back on every run.

Dropping a check from 0.20 seconds to 0.05 seconds is the exact same 4x ratio, and you’ll barely feel it during your day.

Measure the command you run over and over on your own codebase so you know your real baseline. If CI keeps failing with out-of-memory errors, track peak process memory right alongside elapsed time.

Run the native compiler

Let’s start with a tiny project that has a single type error so you can see tsrs work before pointing it at a real codebase.

Create a new folder and install the compiler locally:

mkdir tsrs-demo
cd tsrs-demo
npm init -y
npm install --save-dev tsrs

The npm package downloads the right native binary for your system, so you don’t need Rust installed. Check the platform support table if you plan to run it on another OS or architecture.

Save this config as tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "target": "ESNext",
    "module": "ESNext"
  },
  "include": ["app.ts"]
}

Now add app.ts with a deliberate type mismatch:

function greet(name: string) {
  return `Hello, ${name}`
}

console.log(greet(42))

Run the type check:

npx tsrs -p . --noEmit

tsrs flags the number passed to a string parameter and exits with a non-zero status code, which lets CI fail the build when a check catches an error.

Change the last line to console.log(greet('Flavio')) and run the command again. The error goes away.

Here -p . tells tsrs to read the project in the current folder, and --noEmit skips writing JavaScript files. If you want a refresher on these options, I covered them in my tsconfig.json guide.

Produce JavaScript and declaration files

To test emitting JavaScript and type declarations, replace app.ts with this version:

export function greet(name: string) {
  return `Hello, ${name}`
}

console.log(greet('Flavio'))

Now compile it with declaration files turned on and send the output to a separate folder:

npx tsrs -p . --outDir dist --declaration --noEmitOnError

You’ll get dist/app.js with the type annotations stripped, plus dist/app.d.ts with the exported function’s signature:

export declare function greet(name: string): string

The .d.ts file only keeps the public type signature, leaving the implementation out.

Pass --noEmitOnError if you want a type error to block file generation. Without that flag, the compiler reports the error and still writes the JavaScript files.

Watch and incremental checking

While you’re actively editing code, you can run the native CLI in watch mode:

npx tsrs -p . --noEmit --watch

Leave the terminal running, change the argument in app.ts, and save. The watcher picks up the change and re-runs the check until you hit Ctrl-C.

If you run separate checks instead of keeping a watcher open, turn on incremental mode so the compiler reuses build info from earlier runs:

npx tsrs -p . --noEmit --incremental

When you benchmark, keep the cache state identical across runs. Comparing a warm incremental check against a cold full check will skew the numbers.

The usage guide lists the platform details for native watch mode. The WebAssembly build has its own limits, which we’ll get to in a moment.

Add it to an existing project carefully

Start by adding a separate script to your project and leave your current type check untouched while you compare the two.

Here’s how you can wire both scripts side by side in package.json:

{
  "typecheck": "tsc -p . --noEmit",
  "typecheck:tsrs": "tsrs -p . --noEmit"
}

Run both commands after the exact same dependency install and codegen steps. If your usual check relies on generated database types, tsrs needs those generated files on disk too.

Double-check which files your tsconfig.json picks up, especially in a multi-package monorepo. A fast pass doesn’t help much if half the workspace got skipped.

If your repo uses project references with -b, test that mode directly. tsrs supports emitting JavaScript and declaration files across referenced projects, and if you publish .d.ts files to npm you want to verify that real emit run rather than stopping at --noEmit.

Framework files need their own coverage check

Astro components, Vue single-file components, and Svelte files mix templates and markup with TypeScript.

A content mapper extracts the TypeScript parts of those files for the compiler. Right now the compatibility table shows CLI support for content mappers, while language-server support is still incomplete.

Keep your framework’s own checker in place until you verify tsrs gives you the same coverage. A regular .ts pass can come back green while a type error sits inside a component template.

The editor is a separate integration

Installing tsrs in a repo won’t automatically switch the checker inside your editor. The editor runs through a separate path from the CLI:

Project checking and editor checking need separate setupAdding a tsrs check command affects the project command; an editor separately needs an integration that launches the tsrs language server.Adopt tsrsProject checkcommandCompare diagnosticsand coverageEditor integrationLaunch tsrs languageserverCheck diagnosticsand navigation

The native package ships its own language server, launched with tsrs --lsp -stdio, and your editor needs the right integration to talk to it.

Check the editor setup guide for VS Code’s TypeScript native extension and Neovim config instead of pointing a legacy TypeScript server setting at the Rust binary.

Editor support tracks its own compatibility tests and gaps. Compare diagnostics and go-to-definition on your codebase before rolling it out to a team, and check the compatibility table for automatic type acquisition and content-mapper support.

Measure your own project

If you don’t already have the official compiler installed next to tsrs, add both so you can compare them directly:

npm install --save-dev typescript

Pick a clean, repeatable check command and time both compilers with your shell’s time utility on macOS or Linux:

time npx tsc -p . --noEmit --incremental false --pretty false --checkers 4
time npx tsrs -p . --noEmit --incremental false --pretty false --checkers 4

Those commands assume your official compiler is the native Go-based TypeScript release, which accepts --checkers. An older JavaScript-based tsc will reject that flag.

Run each command a few times in alternating order, and close anything heavy running in the background. Keep in mind that npx startup overhead sits inside these numbers, so on a tiny repo you’ll mostly be timing the launcher.

Log both versions with npx tsc --version and npx tsrs --version. Comparing against the official stable release makes sense when deciding whether to adopt tsrs, while debugging a correctness mismatch calls for comparing against the exact upstream TypeScript revision tsrs targets.

To measure peak memory, use /usr/bin/time -l on macOS or /usr/bin/time -v with GNU time on Linux. Both report maximum resident set size, with different labels and units, so keep the raw units next to your numbers.

Tune only after measuring

Alongside the standard TypeScript flags, the native CLI exposes a few performance knobs:

OptionWhat it controlsTradeoff
--checkers 4Number of type-checking workersMore workers can raise peak memory
--singleThreadedSingle-threaded executionLess concurrency can slow down large runs
--maxMemory 2GMemory target for --noEmit checkingRecycles checker state and can repeat work
--checkerCostCache .tsrs-costsSaves file-checking costs between runsWrites a cache file for later scheduling

Treat --maxMemory as a soft target that tells tsrs to recycle checker state around that threshold. If you need a hard cap, set it at the OS or container level.

If you spot an error difference that looks tied to checking order, the defaults document covers --checkerAssignment go and --noLazyMembers. Both flags help line up behavior with the pinned Go implementation on edge cases like instantiation depth and checking history.

Leave those flags alone during a normal first trial, and reach for them only when you’re narrowing down a specific mismatch.

Why WebAssembly changes where the compiler can run

A native compiler binary only runs on the operating system and CPU it was compiled for. A WebAssembly module runs anywhere a host provides the interfaces it expects.

The @tsrs/wasm package compiles the same Rust compiler core to WebAssembly and wraps it in a JavaScript API for Node and browsers.

In the browser, you pass an in-memory filesystem with filenames and file contents, including your tsconfig.json and any dependency type declarations. Standard TypeScript library declarations come bundled in.

That unlocks a lightweight playground right in the browser with no backend compiler service. A reader tweaks a code snippet, clicks a button, and gets real compiler errors locally.

Fig 3 · 1/5From a browser edit to a compiler diagnostic
Supply a virtual project

Those steps trace the whole loop: files going in, type checking inside a worker, the error coming back, and the clean pass once you fix the code. Each check runs on the snapshot of files you send, so typing in the textarea won’t change a request that’s already running.

If WebAssembly is new to you, my WebAssembly tutorial covers modules, imports, and memory.

Put the compiler in a Web Worker

Loading the Wasm module is asynchronous, while the type check itself runs synchronously on whichever thread calls it.

Calling an async function from your main page script still blocks the UI thread once compilation starts. Putting it in a Web Worker keeps the page responsive while the check runs. @tsrs/wasm doesn’t create a worker for you, so we’ll wire one up in the example below.

Know which filesystem the compiler sees

A browser worker has no access to your local project folder. It only sees the virtual files you include in the request.

For a single snippet, that’s straightforward. Once your code imports a package, you also need to supply its type declarations and resolution paths, or the compiler will complain about a missing package.

If you include @types/node, the compiler gets the type definitions for Node APIs, though the browser still can’t run those APIs.

Compiler state and memory have limits

@tsrs/wasm caches the compiled Wasm module, then creates a fresh instance for every API call. It doesn’t keep a live TypeScript program warm between keystrokes.

Incremental builds can reuse files like .tsbuildinfo, as long as you pass those generated files back into the next request yourself. Keeping the worker alive won’t preserve them automatically.

Right now, the Wasm build is single-threaded and skips --watch, the language server, and the native API-server mode.

Each instance tops out at 4 GiB of linear memory, and the browser may cap it well below that. Deeply recursive types can also blow through the execution stack.

The memoryBytes value returned by the API tracks peak linear memory, including the module’s shadow stack. That’s a different measurement from total browser tab memory or native process RSS, so don’t compare them side by side.

Cloudflare also points to Workers as a big reason to bet on Rust and Wasm. Running a compiler toolchain there still needs its own filesystem and runtime wiring, so the demo below sticks to the browser.

Build a browser-based type checker

Let’s build a small page with a textarea, a Check button, and an output area. The compiler will run inside a dedicated Web Worker. We’ll only type-check the submitted code without executing it.

Start with a recent Node.js version, create a fresh folder, and install Vite along with @tsrs/wasm:

mkdir tsrs-browser-demo
cd tsrs-browser-demo
npm init -y
npm install --save-dev vite
npm install @tsrs/wasm

We’re using Vite so it handles bundling the worker and serving the .wasm file at a predictable URL. You only need three files.

The page

Create index.html with this markup:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TypeScript checker</title>
  </head>
  <body>
    <h1>Check TypeScript in your browser</h1>
    <label for="source">TypeScript source</label>
    <textarea id="source" rows="8" cols="50">const greeting: string = 42</textarea>
    <button id="check" type="button">Check</button>
    <pre id="result" role="status">Ready</pre>
    <script type="module" src="/main.js"></script>
  </body>
</html>

The starter snippet assigns a number to a string so the checker immediately has an error to catch.

The page’s JavaScript

Next, create main.js to wire up the button and talk to the worker:

const source = document.querySelector('#source')
const button = document.querySelector('#check')
const output = document.querySelector('#result')

const worker = new Worker(new URL('./checker.js', import.meta.url), {
  type: 'module'
})

button.addEventListener('click', () => {
  button.disabled = true
  output.textContent = 'Checking...'
  worker.postMessage(source.value)
})

worker.addEventListener('message', ({ data }) => {
  button.disabled = false
  output.textContent = data
})

worker.addEventListener('error', () => {
  button.disabled = false
  output.textContent = 'The compiler worker failed. Reload the page to retry.'
})

Whenever you click the button, the page posts the textarea contents to the worker and disables the button until a response comes back so requests don’t overlap.

If you later turn this into a live editor that checks while you type, you’ll also need to ignore stale replies from earlier keystrokes. Checking on button click keeps this demo simple.

The compiler worker

Now add the worker itself as checker.js:

import { tsc } from '@tsrs/wasm'
import wasmUrl from '@tsrs/wasm/tsrs.wasm?url'

self.addEventListener('message', async ({ data: source }) => {
  try {
    const result = await tsc(['-p', '/project'], {
      url: wasmUrl,
      cwd: '/project',
      diagnostics: 'json',
      files: {
        '/project/tsconfig.json': JSON.stringify({
          compilerOptions: {
            strict: true,
            noEmit: true,
            target: 'ESNext',
            module: 'ESNext',
            moduleDetection: 'force'
          },
          files: ['app.ts']
        }),
        '/project/app.ts': source
      }
    })

    if (result.exitCode === 0) {
      self.postMessage('No type errors')
      return
    }

    const errors = (result.diagnostics ?? []).map((diagnostic) => {
      const line = diagnostic.startPosition
        ? diagnostic.startPosition.line + 1
        : '?'
      return `Line ${line}: TS${diagnostic.code}: ${diagnostic.text}`
    })

    self.postMessage(
      errors.join('\n') || result.stderr || result.stdout || 'Checking failed'
    )
  } catch (error) {
    self.postMessage(`Could not check the code: ${error.message}`)
  }
})

The ?url import gives us Vite’s resolved URL for the .wasm file. Passing it explicitly means we don’t have to rely on the binary landing right next to the bundled JavaScript.

Inside the virtual tsconfig.json, strict mode is on and emit is off. moduleDetection: 'force' makes TypeScript treat the snippet as a module so top-level declarations stay out of the global scope.

Without that option, typing a common variable name like name collides with browser globals. If you want to test classic global-script behavior later, remove moduleDetection: 'force'.

The worker formats any compiler diagnostics into plain text and sends them back to the page. If compilation crashes or the Wasm binary fails to load, it sends back an error message too, so the UI never gets stuck on “Checking…”.

Run it and correct the error

Launch the Vite dev server:

npx vite

Open the local URL Vite prints and click Check. You’ll see error TS2322 telling you a number can’t be assigned to a string.

Fix the code in the textarea to this:

const greeting: string = 'Hello'

Click Check again and you’ll get No type errors.

Try clearing the textarea as well. An empty file is a valid empty module, so it passes with No type errors. A broken compiler load, on the other hand, prints an error message.

Next, verify the production bundle with a build and preview:

npx vite build
npx vite preview

Open the preview URL and run the same checks again. Testing the built output confirms that the bundled worker and .wasm URLs resolve properly outside the dev server.

In this setup, your code only moves between the page and its worker, with no type-checking server involved. The browser still downloads the app’s JavaScript and Wasm asset. If you later add remote package fetching, analytics, or a backend, inspect those network requests before telling users their code never leaves the browser.

Compatibility before adoption

The team maintains a compatibility table in the repo. Check it right before trying tsrs, since support is still moving while the project is experimental.

AreaCurrent boundaryWhat to verify
Ordinary type checkingSupported, with known conformance exceptionsSame files and diagnostics as the matching upstream compiler
JavaScript and declarationsSupportedPublished output files and declaration consumers
Project referencesSupportedYour complete build graph
--init, --showConfigUnsupportedScripts that call these commands
Language serverAvailable natively, with documented gapsNavigation, diagnostics, and editor integration
Framework content mappersCLI support exists; language-server support is incompleteComponents and templates alongside .ts files
WebAssemblySingle-threaded, with separate limitsWorker behavior, asset URLs, and realistic project size

The docs also separate prebuilt platform packages from source builds. Make sure a prebuilt package exists for your target OS and architecture before changing CI runners or asking teammates to install it.

Passing a large upstream test suite is encouraging, though your own repo, editor setup, and runtime config can still surface edge cases worth testing first.

How I would use tsrs

If you have an app with a slow type-checking step, start by adding tsrs as a separate CI job. Let it run beside your existing checker across real commits and pull requests, then dig into any differences.

Write down which TypeScript version each compiler targets, and keep dependency installs, generated files, and project selection identical between the two jobs. Whenever their errors disagree, strip the problem down to a tiny reproduction before deciding which compiler got it right.

Once both checks match, measure the time and memory you save. Being able to run CI on a smaller machine often matters more than shaving seconds off a build that was already fast.

If you maintain a library, diff the generated .d.ts files and run a consumer project against them. If you’re on a framework app, keep the framework’s own type check in place until you verify tsrs covers the same components and templates.

For teaching, start with the browser demo. Letting readers tweak a union type or a generic function right beside a lesson and see the compiler respond immediately makes the concept click faster. Keep those sample projects small so they run smoothly on everyday laptops and phones.

My main advice is not to swap the compiler, editor integration, build output, and CI config in a single change. Move one piece at a time so any discrepancy is obvious and rolling back stays easy.

And if your current type check already finishes quickly and stays out of your way, waiting for a stable release makes complete sense. You can test the experimental build on the parts that matter to your project today while keeping your regular setup untouched.

Want me to talk about your product? You can sponsor this site.

Related posts about typescript: