So now that we know why TypeScript exists, let’s talk about how we use it:
- First, we write TypeScript code in files with the extension .ts.
- Next, we run our code through the TypeScript transpiler. The transpiler will check that the code adheres to TypeScript’s standards, and it will display errors when it does not.
- If the TypeScript code can be converted into working JavaScript, the transpiler will output a JavaScript version of the file (.js).
TypeScript code is a superset of JavaScript code—it has all the features of traditional JavaScript but adds some new features.
Given this TypeScript code as input:
let firstName = 'Anders';
The TypeScript transpiler would output this JavaScript code:
let firstName = 'Anders';
That’s right, they’re the same! TypeScript code generally looks roughly the same as the equivalent JavaScript.
What we’ll learn throughout this lesson and course is the real joy of using TypeScript—that it helps us understand more about our code and, particularly, discover bugs.
Instructions
In this exercise and throughout the lesson, we’ll provide you with a bash terminal to execute your code. We’ll be working with both TypeScript files (files with the extension .ts) and JavaScript files (files with the extension .js).
The TypeScript transcompiler can be used on the command line by running the tsc
command:
tsc
This will create an equivalent .js file in the same directory as well as surface any errors found by the TypeScript transcompiler.
Run the TypeScript transcompiler using the tsc
command.
Great work! You’ve now created an index.js
file (you can confirm this by running the ls
command in your terminal).
Run the resultant JavaScript file with the node
command:
node index.js