typescript-primera-aplicacion

How to Create Your First Application in TypeScript

  • 3 min

Let’s create our first TypeScript application. As usual, our first application will be a “Hello world” (that is, an application that will simply display a message on the screen).

We agree it won’t be the best application you’ll ever make. But it’s the starting point to see the complete process from beginning to end, and to make sure 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 for more complex projects.

Project Setup

Let’s start by creating a new folder for your project (so that your files are 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 hola-mundo-typescript cd hola-mundo-typescript

Write the Code

Now we are going to create our TypeScript application. To do this, simply

  1. Create a file called index.ts in 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));
Copied!

This code,

  • Defines a function greet that takes a name as a parameter and returns a greeting string.
  • Then, 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 don’t “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 execute the following:

tsc index.ts

In fact, we can even run tsc without installing anything on our computer using the npx command from NPM. For example like this:

npx tsc index.html

In either case, the result of running tsc is that it will generate an index.js file in the same folder.

But, normally the first option is used. That is, if we are going to work with TypeScript, we have it installed.

Run the Application

The index.js file we generated with tsc is the resulting JavaScript code from compiling the TypeScript file, and it’s 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 index.js file. We can run it using Node.js:

node index.js

You should see the following output in the terminal:

Hola, Luis!

There we have it! It wasn’t that hard, was it? Now you can start programming like crazy. Or, keep reading the rest of the course to master TypeScript 👍.