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.json
file:
npm init -y
-
Create a TypeScript File: Create a new file named
index.ts
manually or run this command:
touch index.ts
-
Write Your First TypeScript Code: Open
index.ts
in 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.json
file by running:
tsc --init
- Create a
- This command generates a
tsconfig.json
file.
-
Configure File Paths
- Open the
tsconfig.json
file and set therootDir
andoutDir
options:
{ "compilerOptions": { "rootDir": "./module/src", "outDir": "./module/dist" } }
- Open the
-
Create a TypeScript File
- Create a file named
hello.ts
inside themodule/src
directory 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.js
file inside themodule/dist
directory.
-
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)