Getting Started with Typescript | How to Run Your First TS Program

Welcome to the Getting Started with Typescript section where we will kickstart learning Typescript from scratch. Whether you already have some knowledge of Javascript, or not, this tutorial has been created to help you understand Typescript and how it builds itself upon the loosely typed simpler language Javascript.

The first question that comes to mind, of course, is:

What is Typescript?

Typescript is a strictly typed programming language that builds itself on Javascript. It is a static type of language as opposed to the dynamic nature of Javascript. It would be safe to say that it is a superset of Javascript.

The benefits you can reap from using Typescript are plenty.

  • Static Type Checking
  • Leverage OOPS Concepts
  • Dependable
  • Catch Errors in Compilation
  • Consistent
  • Easy Debugging
  • Compatible across Platforms
  • Efficient Tooling Availability
  • Secure

How does Typescript differ from Javascript?

Whether you should or should not proceed with Typescript depends on the complexity of your project. If it is a testing project you are working on, and there are fewer complexities, you can choose Javascript for your project since you don’t have to worry about types there. The latter is simpler to understand too.

Javascript is a dynamically typed language meaning you only get to know about your errors at run time. In Typescript, however, add another step for compilation (just like in Java) where the code is first ‘transpiled’ to Javascript before running. This extra step of compilation or ‘transpilation’ helps you to catch errors in the code early.

Which Language is Better?

There is no ‘which one is better’ here since it really depends on your project requirement. Complex and big projects tend to go with Typescript, however smaller and simpler ones often go with Javascript. Also, the latter is fairly easy to learn. The simplicity of Javascript often makes it a first choice among people who are new to coding. Since Javascript takes away the many nuances of Object Oriented Programming (although that’s not entirely true nowadays) and allows you to code freely.

With Typescript, you tend to adhere to the type rules making the code more robust and error-free. With the inclusion of interfaces, enums, classes (also there in Javascript now), and modules, you tend to catch issues early since code becomes more predictable.

You have to understand that these are not two very different things. I mean Javascript can exist on its own without Typescript. But the first step towards execution is compilation or transpilation in Typescript which basically converts your code to Javascript. So there will be .js files in your explorer. Meaning TS can’t exist without JS.

Getting Started with Typescript – Understanding the Code

Let’s take a look at the most basic code difference.

let s = 34; 

The above if declared in Javascript can be interpreted as both a number and a string. You won’t get any error even if you execute the above code. However, your requirement could be a numeric form of 34 instead of a string, and in your application, you might get an error.

The same thing could have been avoided had you pre-specified the type of the variable in the first step. You can easily do so in Typescript by writing the following:

let  s: number = 34;

Here, as you can see we have added a type number to the variable ‘s’. This is what is called static typing where we define the data type of the variable before using it in the code. Writing the above will restrict the variable ‘s’ to be defined as a number.

Writing your first Program in Typescript

Let’s go ahead and try to execute the above code by adding a console.log(s) to print the result.

Ideally, you should use Visual Studio Code for coding in Typescript since it provides native Typescript support. IDEs like VSC and Webstorm are preferred to others for that reason and their numerous features like code completion, type checking, and refactoring.

But yeah you are not limited to using this particular IDE.

Step 1: Open VSC

Step 2: Open an empty folder in VSC

Step 3: Create a new file with the extension .ts

NOTE: Remember VSC includes Typescript language support but it does not include Typescript compiler. Hence we need to install tsc.

Step 4: Open the terminal and install Typescript using the following command, (if you want to install it globally):

npm i -g typescript

and press enter.

Doing so will do the installation and you might get a similar message saying the package was added.

If you want to make a typescript project or user-restrictive, you can alternatively use the following command:

npm install typescript --save-dev

This will additionally create a package.json where the dependency info will get stored. We are using –save-dev to save it as a dev dependency.

The above code will also create a node_modules folder where the TSC or compiler will be stored which you then can run using npx tsc command.

NOTE: Remember, you will need a copy of Node.js on your system and npm installed to run the package using npm. I am assuming you have already installed Node and NPM on your system first. You can do a simple check to verify if you have installed it already.

Open the command prompt and type:

node -v

and press enter.

For npm verification, type

npm -v

and press enter.

If you get version info, that means you already have it. If not please install npm first.

Step 5: Whether typescript has successfully installed, can be checked by typing:

tsc -version 

and pressing enter. Say hi to ‘tsc’ which is the Typescript compiler; you will be needing it everytime you want to compile your code.

If you get the version info, when you press enter, it means Typescript has been installed globally.

Step 6: Time to add the above code in the .ts file that you created. Go ahead and open the .ts file and write the following:

let s: number = 34;
console.log(s);

It might look something like this:

Step 7: Once you are done, it is time to compile the code. Open the terminal and type the following command:

tsc testing.ts

where testing is the name of the file you gave (visible in the explorer). tsc command is the command for compiler which is supposed to be followed by the name of the file you want to compile.

Press enter.

Step 8: The moment you press enter you will notice that nothing really happened except the same filename with a .js extension got created in the explorer.

If you open the testing.js file, you will notice that its compatible code has been created which looks like this:

What you have witnessed is the process of ‘transpilation’ wherein your .ts code was converted to a .js file.

Step 9: Now you have to execute the .js file to check the result. Just type the following:

node testing.js

and press enter to use Node.js to execute the created .js file.

You will get the result as shown in the image above.

But did you notice? There is something odd here.

Block-Scoped Variable

There seems to be a problem with the above result. On looking closely, you might see that our testing.ts is showing an error that says:

Cannot redeclare block-scoped variable

We are getting this error because there is already a variable re-declaration. If you notice both testing.js and testing.ts have the same variable ‘s’ being defined. But you might say it is in a different file, why are we still getting an error?

The reason is that our files do not have a top-level import or export meaning they are available throughout the project. According to Typescript, a file without any top-level import or export declarations is considered a script, their content is available throughout the global scope.

So one thing is clear – we gotta use import and export throughout Typescript to get rid of such compilation errors.

How to Fix the Block-Scoped Variable Error?

One thing that seems obvious is to update the name of the variable in one of the files. However, this is not ideal since in a project you might be required to work on countless such scenarios. You can’t just update the names of your variables after every compilation. To avoid that, you can just add an export to the testing.ts file to turn it into a module.

Let’s try that:

Add export {} after your code in your .ts file like this:

Woah! The error is gone at once.

But using export here means that you want to share this file across, but what if you don’t?

Another way would be to put it inside a local scope like this:
Just surround the code with curly braces.

{
let s: number = 34;
console.log(s);
}

This means it is inside a local scope. The compiler would not look into the scope unless specifically requested, treating it to be a separate scope.

The error is gone with this too.

But what’s the one kick solution that serves for everything and you don’t have to juggle between defining something inside scope or even exporting something unnecessarily?

In comes tsconfig.json

Using tsconfig.json

In an ideal world, this is the first step you should be doing in any Typescript project. That is creating a tsconfig.json. But I wanted to come to this last, coz I wanted you to understand its very need.

Go ahead and create a tsconfig.json file in your source explorer.

Oh boy! The moment you create it, even though it is empty, the error disappears. It is as if creating the tsconfig.json file alone defines a compiler. Actually, it kind of does. It uses the default compiler options available to configure your project for you. Isn’t that cool?

So what are the default compiler options that come:

  • target is ES5.
  • module system is CommonJS.
  • strict mode is enabled.
  • noImplicitAny option is enabled.
  • outDir option is set to current directory.

That insinuates that even if you leave your tsconfig.json empty, it will still use the above options to help you compile your code and eliminate module-related errors. Pretty clean, huh!

You can use npx tsc –init to create a tsconfig.json as well, the details of which we will see in the next chapter.

Let me know how useful you found our getting started with the Typescript tutorial to be in the comments section. Explore tons of other tutorials in Dumb IT Dude.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

1 Response

  1. March 12, 2024

    […] way would be to manually go ahead and create tsconfig.json like we did last time in the Getting Started with Typescript tutorial. However, since Typescript comes loaded with features why not exploit […]

Leave a Reply