28.6. Compiling TypeScript¶
In this section, you will install the compiler and then practice compiling and running a small TypeScript program from the terminal.
To install TypeScript, in your terminal, type
$ npm install -g typescript
Mac users: You may receive a permissions error when running this install command. If you do, try running it as sudo.
Once you have TypeScript installed, you'll be able to run
$ tsc -v
tsc is the TypeScript compiler and
-v is the version flag to show us that
we have TypeScript and it's compiler installed.
In true tutorial form, let's write a quick
Hello, World program so we can see this
compiling in action.
In your code editor, create a new file called
hello_world.ts. In it, initialize a
message with the string value
'Hello, World'. Print the message.
let message: string = 'Hello, World'; console.log(message);
Make sure to save your
hello_world.ts changes before continuing forward!
In the terminal, navigate into the directory that houses your
Compile the code with the following command:
$ cd Desktop/ $ ls hello_world.ts $ tsc hello_world.ts $ ls hello_world.js hello_world.ts
If your TypeScript file is free of syntax errors, you won't see a response from the
terminal directly. However, you should see that you now have a newly generated file
in your working directory called
hello_world.js. Open it up and take a look!
$ node hello_world.js Hello, World
Look at that! Your message printed. You're now running your own code straight from the terminal!
You'll need these compiling and executing steps for the exercises in the following section, so refer back here as needed.