Language: EN

typescript-primera-aplicacion

How to Create Your First Application in TypeScript

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 it will not be the best application you make in your life. But it is the starting point to see the complete process from beginning to end, and to ensure that 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, not scattered all over your computer 😉).

So we create a folder, either with the file explorer or by running the following command in the terminal:

mkdir hello-world-typescript
cd hello-world-typescript

Writing the Code

Now let’s create our TypeScript application. To do this, simply

  1. Create a file named index.ts at the root of your project.
  2. Open the file index.ts in your text editor or IDE.
  3. 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 have 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 post how to install TypeScript, we run 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, that 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 index.js file that we generated with tsc is the resulting JavaScript code from the compilation of the TypeScript file, and it is what 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 got it! It hasn’t been that difficult, right? Now you can start coding like crazy. Or, keep reading the rest of the course to master TypeScript 👍.