Running TypeScript files via the command line requires several steps. I will walk you through the process step by step.
Step 1: Install Node.js
Ensure that your computer has Node.js installed. Node.js is a JavaScript runtime that enables you to run JavaScript code on the server side. If you haven't installed Node.js yet, visit the official website to download and install it:
Step 2: Install TypeScript
Install the TypeScript compiler via the command line. Installing TypeScript globally using npm ensures that the ts-node command is available anywhere.
shellnpm install -g typescript
Step 3: Install ts-node
ts-node is a tool that executes TypeScript files and runs them directly in the Node.js environment. It automatically compiles TypeScript code into JavaScript in the background and executes the converted code immediately.
shellnpm install -g ts-node
Step 4: Write TypeScript Code
Create a new TypeScript file in your preferred text editor, such as example.ts, and write TypeScript code. For example:
typescript// example.ts function greet(person: string) { return "Hello, " + person + "!"; } console.log(greet("world")); // Output: Hello, world!
Step 5: Run the TypeScript File
Open the command line tool, navigate to the directory containing the example.ts file, and run it using the following command:
shellts-node example.ts
Sample Output:
plainHello, world!
ts-node automatically compiles the example.ts file into JavaScript and executes it in the Node.js environment.
This completes the steps to run TypeScript files via the command line.