How to run TypeScript files from command line?
You can run TypeScript files from the command line by compiling them to JavaScript with the tsc
(TypeScript compiler) and then running the resulting JavaScript with node
. Alternatively, you can use tools like ts-node
to execute TypeScript directly without a separate compile step.
Below are the most common approaches:
1. Using tsc
and node
- Install TypeScript (globally or in your project):
npm install -g typescript # or, locally: npm install --save-dev typescript
- Compile your
.ts
file to.js
:tsc myFile.ts # Generates myFile.js (and possibly a .d.ts if configured)
- Run the generated JavaScript with
node
:node myFile.js
This approach separates compilation (tsc
) from execution (node
).
Example
tsc main.ts # produces main.js node main.js # runs the compiled JS
2. Using ts-node
(Run TS directly)
- Install
ts-node
(and TypeScript, if not installed):npm install -g ts-node typescript # or, locally: npm install --save-dev ts-node typescript
- Run your
.ts
file directly:ts-node myFile.ts
ts-node
compiles your TypeScript on the fly and executes it immediately (like a REPL for TS).
Example
ts-node main.ts
No separate .js
file is needed—very convenient for quick scripts or development workflows.
3. Using npx
(No Global Installs)
If you have TypeScript and ts-node
installed locally in a project, you can use npx:
npx tsc main.ts # compiles with local tsc npx ts-node main.ts
This runs the local versions without installing them globally.
4. Typical Project Setup
- A
tsconfig.json
file configures how TypeScript compiles your code (target version, strictness, outDir, etc.). - You can have npm scripts in your
package.json
like:{ "scripts": { "build": "tsc", "start": "ts-node src/main.ts" } }
- Then simply run:
npm run build # compiles npm start # runs via ts-node
5. Summary
- Option A: Compile with
tsc
, then run the resulting.js
withnode
. - Option B: Use
ts-node
to run.ts
files directly for convenience (no separate.js
needed). - Option C: Combine with npm scripts or npx for local usage and project automation.
Bonus: Strengthen Your JavaScript (and TypeScript) Fundamentals
TypeScript builds on core JavaScript concepts. If you want to deepen your JS knowledge—covering prototypes, closures, async patterns, etc.—consider the Grokking JavaScript Fundamentals course by DesignGurus.io. This foundation translates directly to writing better, more maintainable TypeScript code.