Let’s create our first TypeScript application. As usual, our first application will be a “Hello world” (that is, an application that simply displays a message on the screen).
We agree that this will not be the best application you’ll ever make. But it is the starting point to see the complete process from beginning to end, and ensure everything works.
So let’s get to it! 👇
By the end of this article, we will have a basic understanding of how to work with a TypeScript project and well… more or less the process is the same in more complex projects.
Project setup
Let’s start by creating a new folder for your project (just to keep your files organized, and not scattered all over your computer 😉).
So we create a folder, either with the file explorer or with the terminal by executing the following command:
mkdir hello-world-typescript
cd hello-world-typescript
Normally, we would use TypeScript to initialize this folder. We will see it in the next article How to create a project
But for this example, a blank folder is enough for now.
Writing the code
Now let’s create our TypeScript application. To do this, simply
- Create a file named
index.ts
in the root of your project. - Open the file
index.ts
in your text editor or IDE. - Write the code copied from the following example,
function greet(name: string): string {
return `Hello, ${name}!`;
}
const name = "Luis";
console.log(greet(name));
This code:
- Defines a function
greet
that takes a name as a parameter and returns a greeting string. - Then, it defines a constant
name
with the value “Luis”. - Calls
console.log
to print the greeting to the console.
Compile the TypeScript code
Now that we have our simple TypeScript application, we need to compile the TypeScript code to JavaScript.
Most programs like the browser or Node.js do not “know” how to execute TypeScript. We need to convert it to JavaScript, for which we will use the TS compiler tsc
.
To do this, if we have installed TypeScript as we saw in the entry how to install TypeScript, we execute the following,
tsc index.ts
In fact, we can even run tsc
without needing to install anything on our computer with the npx
command from NPM. For example, like this,
npx tsc index.html
In either case, the result of running tsc
will generate a file index.js
in the same folder.
But come on, the normal is the first option. That is, if we are going to work with TypeScript, we should have it installed.
Run the application
The file index.js
that we generated with tsc
is the JavaScript code resulting from the compilation of the TypeScript file, and it is the one we can execute or incorporate into our web page.
In our example, we now have our “Hello World” application saved in the generated file index.js
. We can run it using Node.js:
node index.js
You should see the following output in the terminal:
Hello, Luis!
We’ve got it! It really hasn’t been that difficult, right? Now you can start coding like crazy. Or, keep reading the rest of the course to master TypeScript. 👍