Install TypeScript and Write a Simple TypeScript Program
Objectives:
- Set up a TypeScript development environment.
- Write and run a simple TypeScript program.
Steps:
-
If you haven't already created a project directory, do so and navigate into it:
bashmkdir typescript-basicscd typescript-basics -
Initialize a new Node.js project:
bashnpm init -y -
Install TypeScript as a local dependency:
bashnpm install typescript --save-dev -
Create a TypeScript configuration file:
json// tsconfig.json{"compilerOptions": {"target": "es5","module": "commonjs","strict": true,"outDir": "./dist","rootDir": "./src"},"exclude": ["node_modules"],"include": ["src"]} -
Create a
src
directory. This is where we will put our.ts
typescript files.bashmkdir src -
Write a Simple TypeScript Program:
- Create a new file named
index.ts
in thesrc
directory. - Open
index.ts
in your text editor and add the following code:
ts// index.ts// Define a variable with a string type?? = "Hello, TypeScript!";// Define a function that returns a greeting messagefunction greet(name: string){return `${greeting} Welcome, ${name}!`;}// Call the function and log the resultconsole.log(greet("Student")); - Create a new file named
-
Compile the TypeScript Code:
- Compile your TypeScript code to JavaScript using the TypeScript compiler. Run the following command in your terminal:
bashnpx tsc- This will generate a
dist
directory and a file namedindex.js
inside it with our compiled code.
-
Run the JavaScript Code:
- Run the compiled JavaScript code using Node.js:
bashnode ./dist/index.js- You should see the output:
Hello, TypeScript! Welcome, Student!
.