Introduction
In this post, I will show you how to run TypeScript without compiling it to JavaScript first. This is useful for debugging and testing.
Set up a TypeScript project
Step 1: create a directory
Create a directory for the project.
# Create a directorymkdir run-typescript-without-compiling
# Change directorycd run-typescript-without-compilingStep 2: initialize a Node.js project
Initialize a Node.js project.
# Initialize a Node.js projectpnpm initStep 3: install TypeScript and @types/node
Install TypeScript and @types/node.
# Install TypeScript and @types/nodepnpm add -D typescript @types/nodeStep 4: initialize a TypeScript project
Initialize a TypeScript project.
# Initialize a TypeScript projectpnpm exec tsc --initStep 5: create a TypeScript file
Create a TypeScript file.
# Create a src directorymkdir src
# Create a TypeScript filetouch src/index.tsStep 6: example code
Add the following code to the TypeScript file.
const sum = (a: number, b: number): number => a + b;const subtract = (a: number, b: number): number => a - b;const multiply = (a: number, b: number): number => a * b;const divide = (a: number, b: number): number => a / b;
console.log(sum(1, 2));console.log(subtract(1, 2));console.log(multiply(1, 2));console.log(divide(1, 2));Step 7: run the TypeScript file
Now we install tsx and run the TypeScript file directly. tsx supersedes
the older ts-node for this job: it is faster, needs no configuration, and has
a watch mode built in, so it replaces ts-node, esr and nodemon with a
single dependency.
# Install tsxpnpm add -D tsxAdd the following code to the package.json file.
{ ... "scripts": { "playground": "tsx src/index.ts", "playground:watch": "tsx watch src/index.ts", "build": "tsc", "build:watch": "tsc -w", "build:debug": "tsc --sourceMap", "build:debug:watch": "tsc -w --sourceMap", "start": "node dist/index.js", "start:watch": "node --watch dist/index.js" }, ...}Note
No extra watcher is needed. tsx watch restarts on changes to your TypeScript
sources, and node --watch does the same for the compiled output in dist -
it has been built into Node since 18.11, so there is nothing to install for
either.
Run the TypeScript file.
# Run the TypeScript filepnpm playground
# Output3-120.5Conclusion
In this post, I showed how to run TypeScript without first converting it to JavaScript. For testing and troubleshooting, that is helpful.
References
- TypeScript Official Website
- TypeScript Documentation
- ts-node on npm
- ts-node GitHub Repository (TypeStrong/ts-node)
- tsx on npm
- Node.js watch mode
- Node.js Official Website
- Node.js Documentation
- Yarn Package Manager
- TypeScript
tsconfig.jsonReference - npm
package.jsonGuide @types/nodepackage on npm (for Node.js type definitions)- TypeScript Playground (for quick experiments)








