TypeScript Installation
To start using TypeScript, you need to install the TypeScript compiler (tsc). The compiler is responsible for converting TypeScript code (.ts files) into JavaScript code (.js files) that browsers or Node.js can run.
The most common way to install TypeScript is through npm (Node.js package manager). Therefore, before installing TypeScript, make sure Node.js and npm are already installed on your system.
1. Check Node.js and npm
Open your terminal or command line tool and enter the following commands to check if Node.js and npm are installed:
node -v
npm -vIf the commands return version numbers (e.g., v18.17.0), they are successfully installed. If the command is not found, you need to visit the Node.js official website to download and install it. npm will be installed along with Node.js.
2. Install TypeScript Globally
We typically install the TypeScript compiler globally, so you can use the tsc command anywhere in any project.
Run the following command in your terminal:
npm install -g typescriptnpm installis the installation command.- The
-gflag means "global," meaning this package will be installed in the system's global directory, not in the current project. typescriptis the name of the package we want to install.
After installation is complete, you can verify that TypeScript is successfully installed and check its version with the following command:
tsc -vIf successful, it will output the TypeScript compiler version number, such as Version 5.2.2.
3. Write Your First TypeScript File
Now that you have TypeScript installed, you can write your first TypeScript file.
- Create a new folder, for example
ts-project. - Create a file named
hello.tsin the folder. - Enter the following code in the
hello.tsfile:
function greet(name: string) {
console.log("Hello, " + name + "!");
}
greet("World");Note that we specified the type of the greet function's parameter name as string.
4. Compile TypeScript File
Now, we need to compile the hello.ts file into JavaScript. In the terminal, make sure you are inside the ts-project folder, then run the following command:
tsc hello.tsAfter execution, you will find a new hello.js file in the folder. Looking at its content, you'll see that TypeScript's type annotations have been removed:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("World");5. Run JavaScript File
This generated hello.js file is a standard JavaScript file, which you can run using Node.js:
node hello.jsThe terminal will output:
Hello, World!Congratulations! You have successfully installed TypeScript and completed the compilation and execution of your first program.