Introduction
In this chapter, we will write our first TypeScript program. We will cover the basics of creating a TypeScript file, compiling it, and running the resulting JavaScript file. This will help you understand the workflow of developing with TypeScript and see the benefits of type safety in action.
Table of Contents
- Creating a TypeScript File
- Compiling TypeScript to JavaScript
- Running the Compiled JavaScript
- Conclusion
Creating a TypeScript File
Let's start by creating a simple TypeScript program.
1. Create a src
Directory
First, create a src
directory in your project to hold your TypeScript files:
mkdir src
2. Create a TypeScript File
Next, create a new TypeScript file named index.ts
inside the src
directory:
touch src/index.ts
3. Write Your TypeScript Code
Open src/index.ts
in your code editor and add the following code:
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}! Welcome to TypeScript.`;
}
const userName = "Ravi";
console.log(greet(userName));
Explanation:
- We defined a
greet
function that takes aname
parameter of typestring
and returns astring
. - We then declared a
userName
variable and assigned it the value"Ravi"
. - Finally, we called the
greet
function withuserName
and logged the result to the console.
Compiling TypeScript to JavaScript
Now that we have written our TypeScript code, we need to compile it to JavaScript so that it can be executed by a JavaScript engine.
1. Compile the TypeScript File
Open your terminal and run the TypeScript compiler:
npx tsc
This command will compile all TypeScript files in the src
directory according to the configuration specified in tsconfig.json
.
2. Check the Output
After running the TypeScript compiler, you should see a new dist
directory (or build
, depending on your tsconfig.json
settings) containing the compiled JavaScript file:
ls dist
index.js
Running the Compiled JavaScript
To see the output of our program, we need to run the compiled JavaScript file using Node.js.
1. Run the JavaScript File
Use the following command to run the index.js
file in the dist
directory:
node dist/index.js
2. Verify the Output
You should see the following output in your terminal:
Hello, Ravi! Welcome to TypeScript.
TypeScript Playground
If you feel the setup is time-consuming, you can use the official online TypeScript Playground tool to quickly compile and run the TypeScript code.
Conclusion
In this chapter, we wrote our first TypeScript program. We created a TypeScript file, compiled it to JavaScript, and ran the resulting JavaScript file. This process demonstrated the basic workflow of developing with TypeScript.
Comments
Post a Comment
Leave Comment