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.
The TypeScript compiler can be installed globally on your machine via npm (Node Package Manager) using the following command:
npm install -g typescript
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.
Let's see a simple TypeScript example and its compiled JavaScript output.
// 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.
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.
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
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.