· Jake Worth

Running TypeScript in a REPL with tsx


Interested in running TypeScript in a local REPL (Read, Evaluate, Print, and Loop)? Check out tsx (“TypeScript Execute”):

$ npx tsx

It evaluates JavaScript and TypeScript!

> const onClick = (input: number): void => input + 1;
undefined
> onClick(1);
2

An important distinction is that tsx can transpile TypeScript to JavaScript, but it does not type-check it. So, this unsafe code runs just fine:

// Number type disagrees with string literal assignment
const greeting: number = 'Hello world!';

To get type-checking, you’ll need a compiler like tsc. Here’s a quick way to take the code evaluated in your tsx session and compile it with tsc. Save it:

.save output.ts

And run it:

$ npx tsc output.ts
output.ts:1:7 - error TS2322: Type 'string' is not assignable to type 'number'.
1 const greeting: number = "Hello world!;"
~~~~~~~~
Found 1 error in output.ts:1
  • tsx — official site
  • Node.js REPL — Node.js docs (.save and other REPL commands)