To install TypeScript and compile a .ts file, follow these steps:
1. Install Node.js: TypeScript is a superset of JavaScript and requires Node.js to work. Download and install Node.js from the following link: [https://nodejs.org/en/download/] (https://nodejs.org/en/download/)
2. Install TypeScript: After installing Node.js, open your terminal or command prompt, and type the following command to install TypeScript globally:
npm install -g typescript
3. Create a ‘.ts‘ file: Create a TypeScript file with the extension ‘.ts‘. For example, create a file named ‘example.ts‘. Add this code to the file:
function greet(name: string) {
return 'Hello, ' + name + '!';
}
let user = 'TypeScript User';
console.log(greet(user));
4. Compile the TypeScript file: In your terminal or command prompt, navigate to the directory containing the ‘example.ts‘ file. Run the following command to compile the TypeScript file to JavaScript:
tsc example.ts
This command will generate a new file named ‘example.js‘ containing the JavaScript equivalent of your TypeScript code.
5. Execute the compiled file: Now that you have the compiled JavaScript file, you can execute it using Node.js:
node example.js
This command will return the output ‘Hello, TypeScript User!‘.
Here’s a summary of the process:
Install Node.js: Download and install Node.js from https://nodejs.org/en/download/.
Install TypeScript: Run
npm install -g typescriptin the terminal/command prompt.Create a .ts file: Create a file named
example.tswith the sample TypeScript code.Compile the TypeScript file: Navigate to the directory containing the
example.tsfile and runtsc example.ts.Execute the compiled file: Run
node example.jsto see the output ‘Hello, TypeScript User!‘.