Well, because not all browsers support TypeScript yet, so by converting it to JavaScript, we can make sure everyone can use our awesome code.
So how does this magic happen? Let’s say we have a file called `my-script.ts` with some fancy TypeScript code:
// my-script.ts
// This is a TypeScript script that will be converted to JavaScript for compatibility with all browsers.
// Declaring a variable named 'myVar' of type string and assigning it the value of 'hello world'.
const myVar: string = "hello world";
// Defining a function called 'printHello' that does not take any arguments and prints 'hello' to the console when executed.
function printHello(): void {
console.log("hello"); // Using the built-in JavaScript method 'console.log' to log 'hello' to the console.
}
Now, we want to convert this TypeScript file into a regular old JavaScript file that can be used by any browser. To do this, we use a tool called `tsc`. This is like a translator for our code it takes in TypeScript and spits out JavaScript. Here’s what the command looks like:
# In your terminal or command prompt
$ tsc # Runs 'tsc' which transpiles all .ts files in the current directory to their corresponding .js files.
Once we run this command, `tsc` will convert our TypeScript code into JavaScript and create a new file called `my-script.js`. This is what it looks like:
// my-script.js (generated by tsc)
"use strict"; // This line enables strict mode, which helps prevent errors in our code.
let myVar = "hello world"; // This line declares a variable called 'myVar' and assigns it the value of 'hello world'.
function printHello() { // This function called 'printHello' does not take any arguments and prints 'hello' to the console when it is executed.
console.log("hello"); // This line logs 'hello' to the console using the built-in JavaScript method 'console.log'.
}
// The following script declares a variable and a function, and uses the built-in console.log method to print a message to the console.
As you can see, `tsc` has converted our TypeScript code into regular old JavaScript that any browser can understand! And now we have a new file called `my-script.js` that we can use in our projects without worrying about compatibility issues. Pretty cool, huh?