Compiling TypeScript Code with tsc

Tutorial 3 of 5

1. Introduction

In this tutorial, we aim to help you understand how to compile TypeScript code using the TypeScript compiler (tsc). By the end of this tutorial, you will learn how to convert your TypeScript code into JavaScript using the tsc compiler.

Prerequisites: Basic familiarity with TypeScript and JavaScript. You should also have Node.js and npm installed on your machine.

2. Step-by-Step Guide

Installing TypeScript

The TypeScript compiler can be installed globally on your machine via npm (Node Package Manager) using the following command:

npm install -g typescript

Compiling TypeScript to JavaScript

Once TypeScript is installed, you can compile a .ts file to .js by using the tsc command followed by the file name.

tsc filename.ts

This will generate a new file filename.js in the same directory.

3. Code Examples

Let's see a simple TypeScript example and its compiled JavaScript output.

Example 1: Simple TypeScript Code

// filename.ts
let message: string = 'Hello, TypeScript!';
console.log(message);

To compile this TypeScript file to JavaScript, run:

tsc filename.ts

This will create a new file filename.js with the following JavaScript code:

// filename.js
var message = 'Hello, TypeScript!';
console.log(message);

As you can see, TypeScript's type annotation has been removed in the JavaScript output, since JavaScript does not support static typing.

4. Summary

In this tutorial, we've learned how to compile TypeScript code to JavaScript using the tsc compiler. The next step would be to learn more advanced TypeScript features and how they translate into JavaScript.

You can refer to the official TypeScript documentation for more detailed information and additional resources.

5. Practice Exercises

  1. Create a TypeScript file that defines a function to add two numbers. Compile it to JavaScript using the tsc compiler.

Solution:

// add.ts
function add(a: number, b: number): number {
  return a + b;
}

console.log(add(2, 3));  // Outputs: 5

To compile, run: tsc add.ts

  1. Modify the above TypeScript file to use arrow functions. Compile it to JavaScript.

Solution:

// add_arrow.ts
const add = (a: number, b: number): number => {
  return a + b;
}

console.log(add(2, 3));  // Outputs: 5

To compile, run: tsc add_arrow.ts

Keep practicing different TypeScript concepts and compiling them to JavaScript to understand how they translate into JavaScript.