TypeScript is a superset of JavaScript that adds optional static typing to the language. It was developed by Microsoft and has gained popularity among developers due to its ability to catch errors at compile time and improve code maintainability. In this tutorial, we will cover the basics of getting started with TypeScript.


Installing TypeScript

The first step in getting started with TypeScript is to install it. TypeScript can be installed using npm, which is the package manager for Node.js.

To install TypeScript globally, run the following command in your terminal:

npm install -g typescript

Once installed, you can check the version of TypeScript by running the following command:

tsc --version


Creating a TypeScript file

To create a TypeScript file, create a new file with the .ts extension. For example, let's create a file named app.ts. In this file, we can write TypeScript code just like we would with JavaScript.

function greet(name: string) {
  console.log("Hello, " + name);
}

greet("TypeScript");

In this code, we define a function greet that takes a string parameter name and logs a greeting to the console.


Compiling TypeScript

To compile the TypeScript code into JavaScript, we need to run the TypeScript compiler. We can do this by running the following command in the terminal:

tsc app.ts

This will generate a JavaScript file named app.js in the same directory as the TypeScript file.


Using TypeScript with a Project

When working on a larger project, it's a good idea to organize your files into a directory structure. TypeScript supports this by allowing us to use modules.

Let's create a new directory named src and create a new file named index.ts inside it. This will be the entry point for our application.

// src/index.ts
import { greet } from "./greet";

greet("TypeScript");

In this code, we import the greet function from another file named greet.ts in the same directory. Let's create that file now.

// src/greet.ts
export function greet(name: string) {
  console.log("Hello, " + name);
}

In this code, we define the greet function and export it so that it can be used in other files.

To compile our project, we can run the following command:

tsc src/index.ts --outDir dist

This will compile all the TypeScript files in the src directory and output the JavaScript files into a directory named dist.


Conclusion

TypeScript is a powerful tool that can improve the quality of your code and make it easier to maintain. In this tutorial, we covered the basics of getting started with TypeScript, including installing TypeScript, creating a TypeScript file, compiling TypeScript, and using TypeScript with a project. With this knowledge, you can start using TypeScript in your own projects and take advantage of its benefits.