TypeScript has become a popular choice for many developers due to its strong typing and excellent tooling support. In this guide, we'll walk you through installing TypeScript and writing your first TypeScript program.
Step 1: Install Node.js and npm
Before installing TypeScript, you need to have Node.js and npm (Node Package Manager) installed. You can download and install them from the official Node.js website.
To check if Node.js and npm are installed, open your terminal and run:
node -v
npm -v
You should see the version numbers for both Node.js and npm.
Step 2: Install TypeScript
Once Node.js and npm are installed, you can install TypeScript globally using npm. Open your terminal and run:
npm install -g typescript
This command installs TypeScript globally on your machine, allowing you to use the tsc command to compile TypeScript files.
To verify the installation, run:
tsc -v
You should see the TypeScript version number.
Step 3: Create Your First TypeScript Program
- Create a New Directory: Create a new directory for your TypeScript project and navigate into it:
mkdir my-typescript-project
cd my-typescript-project
-
Initialize a New Node.js Project: Initialize a new Node.js project to create a
package.jsonfile:
npm init -y
-
Create a TypeScript File: Create a new file named
index.tsmanually or run this command:
touch index.ts
-
Write Your First TypeScript Code: Open
index.tsin your preferred text editor and add the following code:
const welcome:string= "Hello World!"
Step 4: Compile TypeScript to JavaScript
To compile your TypeScript code to JavaScript, use the TypeScript compiler (tsc). In your terminal, run:
tsc index.ts
This command generates a index.js file in the same directory.
Step 5: Run the Compiled JavaScript
Now, you can run the compiled JavaScript file using Node.js:
node index.js
You should see the output:
Hello, World!
Follow these steps to set up TypeScript, configure file paths, and write your first TypeScript program.
-
Create a TypeScript Configuration File
- Create a
tsconfig.jsonfile by running:
tsc --init - Create a
- This command generates a
tsconfig.jsonfile.
-
Configure File Paths
- Open the
tsconfig.jsonfile and set therootDirandoutDiroptions:
{ "compilerOptions": { "rootDir": "./module/src", "outDir": "./module/dist" } } - Open the
-
Create a TypeScript File
- Create a file named
hello.tsinside themodule/srcdirectory and add the following code:
const welcome: string = "Hello World!"; console.log(welcome); - Create a file named
-
Compile TypeScript to JavaScript
- To convert the TypeScript code to JavaScript, run:
tsc
- This will generate a
hello.jsfile inside themodule/distdirectory.
-
Run the Compiled JavaScript File
- Use Node.js to run the compiled JavaScript file:
node module/dist/hello.js
-
You should see the output:
Hello, World!
By following these steps, you've successfully installed TypeScript, configured file paths, and written and executed your first TypeScript program.
Top comments (0)