Introduction to TypeScript

Introduction to TypeScript

In this article, you will learn what TypeScript is all about: its installation, the differences between TypeScript and JavaScript, its basic types and concepts, how to configure TypeScript by adding the tsconfig.json file.

cover.png

WHAT IS TYPESCRIPT?

TypeScript is an open-source Object Oriented Programming language developed and maintained by Microsoft.

TypeScript is a strongly typed language. It is a superset of JavaScript, which means anything that is implemented in JavaScript can be implemented using TypeScript along with the enhanced features provided by TypeScript.

As TypeScript code is converted to JavaScript code which makes it easier to integrate into JavaScript projects. It is designed mainly for large-scale projects.

TypeScript is a primary language for Angular framework. Angular is an open-source web application framework maintained by the Angular Team at Google.

Why we use TypeScript?

1. Static type checking: Like other high-level programming languages like JAVA, TypeScript does provide static type checking which requires some extra code but it has its advantages.

2. Classes and Interfaces: TypeScript supports Classes that provide the ability to use object-oriented programming in our applications. It also provides encapsulation, inheritance, and access modifiers that JavaScript can't offer (In 2015 with ECMA script 6 classes have been introduced but we can't use access modifiers in them unlike TypeScript).

3. Better developer experience: TypeScript code is documentation in itself. Because modern IDEs support TypeScript autosuggestions which is a great tool to develop apps at a faster pace and with fewer bugs.

4. Runs everywhere: TypeScript is technically just JavaScript with enhanced tools. Thus, if you are writing code using TypeScript, it will be converted to JavaScript. It can be used for both front-end development (React, Angular) and back-end development (Node.js).

DIFFERENCE BETWEEN TYPESCRIPT AND JAVASCRIPT

  • TypeScript is known as an Object-oriented programming language whereas JavaScript is a scripting language.
  • TypeScript has a feature known as Static typing but JavaScript does not have this feature.
  • TypeScript has Interface but JavaScript does not have an Interface.
  • TypeScript provides compile-time safety (You will get possible errors while writing code) but JavaScript does not provide compile-time safety (JavaScript throws runtime errors which we can prevent using TypeScript).

REQUIRED TOOLS:

Here is a list of recommended tools that will assist you in getting the most out of TypeScript:

1. VS Code (Install VS Code from https://code.visualstudio.com/) (Since Microsoft maintains TypeScript and VS Code, I believe there is no IDE that provides better support for TypeScript than VS Code.)

2. Node.JS (Install node from https://nodejs.org)

3. NPM

INSTALLATION:

Run the following command in your terminal (make sure to run it as an administrator) to install TypeScript globally

npm install -g typescript

Once done run the following command to check if TypeScript is installed on your machine

npx tsc

As long as you are getting version number and some common commands you are good to go!

LETS SET UP A PROJECT:

Open a folder in VS code and create index.html and index.ts files in it.

Now run the following command to initialize a project.

npm init
// it will ask some questions just hit enter with default options

It will create a package.json file in your root folder

EXTENSION FOR VS CODE USERS:

If you're using VS Code, you can use an extension called live server (published by Ritwick Dey) to have the browser automatically refresh when you save your changes.

Select Extensions > Search for "live server" and then install the first extension written by Ritwick Dey.

PACKAGE FOR NON VS CODE USERS

Run the following command to install a required package:

npm install --save-dev lite-server

This will install live-server as a dev dependency (we only need this for development)

Add start script to start the project. In package.json inside scripts add the following line:

...
 "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "lite-server"
  },
...

If you do not use the live server extension, you have to start the lite-server using the following command:

npm start

FIRST TYPESCRIPT CODE:

Add the following code in your index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Typescript intro</title>
  </head>
  <body>
    <div id="root">
        <p>Hello...</p>
    </div>
    <script src="./index.js"></script> 
  </body>
</html>

Add the following code to the index.ts file to check if our setup is working:

console.log("Hello world!")

To run live server go to index.html > right-click and select Open with live server option. It will start a local server that will serve our index.html file.

For lite-server users run npm start and you are good to go.

Please run the following command to compile our index.ts into index.js since, as I mentioned earlier, our browser only knows JavaScript, so we must compile our TypeScript code into JavaScript.

tsc index.ts -w

tsc is a high-level compiler that outputs a JavaScript file, .js, from a TypeScript file, .ts. As a result of the above command, an index.js file is created in the root directory, which is linked in the index.html file using the script tag.

-w flag in the above command indicates watch mode. The above command will automatically compile the .ts file whenever you make any changes and save the file.

Open the browser and you should see Hello World printed in your browser console.

image.png

To confirm it's working, change the index.ts file, write console.log(Hello World...) in it, and save the file.

Open the browser, you should see Hello World... printed in your browser console without reloading.

image.png

CORE BASIC TYPES IN TYPESCRIPT:

TypeScript has some basic and core types that JavaScript understands as well. These includes:

- number // 1, 2, 3
- string // "Hello", "World"
- object // {name: "John", age: 30}
- boolean // true, false

TypeScript also has a type called Array. However, it is a generic type and is a bit of an advanced topic that we will discuss more in depth in future blogs.

TYPESCRIPT SYNTAX AND SOME EXAMPLES:

number, string and boolean TYPES IN TYPESCRIPT:

Let's write some code to understand the above types.

const a: number = 5; 
const b: string = "hello world";
const c: boolean = true;

Here's how we declare a variable in TypeScript. Here, a is the name of the variable, number is the type of that variable, and 5 is its value.

TYPE INFERENCE:

In the above example, you can omit the : number, : string, or : boolean part since TypeScript automatically infers the type of that variable based on the value you are assigning. That's called Type inference.**

Take a look at the following function, it adds two numbers and returns a sum:


// num1 is a type of number and :number before => mark is the return type of that number
// but typescript detects return type of function automatically most of the time
const add = (num1: number, num2: number):number => {
  return num1 + num2;
};

console.log("ANSWER: ", add(1, 2));

Save the file. Ensure that your tsc index.ts -w command is running. You should now see ANSWER: 3 in the console in your browser.

image.png

Now in the above add function 1st argument num1 is inferred to type number same for num2. We are adding two numbers, and everything is working fine.

Here, in the add function, the first argument num1 is inferred to be of type number, and the same for num2. We are adding two numbers, and everything is working fine.

Let's see what happens if we pass a string in the add function.

image.png

We get a compilation error from TypeScript. You can see this in the above image. In JavaScript, you won't get that error. Instead, you will get strange behavior, and it will print ANSWER: HELLO2 in the console. Because JavaScript converts num2 to a string and concatenates it with HELLO which is unwanted behavior.

TypeScript throws a compilation error. This can be seen in the image above. JavaScript will not throw this error. In this case, you will see abnormal behavior and it will display ANSWER: HELLO2 in the console because JavaScript converts num2 to a string and concatenates that string with HELLO, which is unintended.

It could happen when you are getting value from user input from which you are expecting a number but it's returning a value in string format so if you pass "2" and "3" to the above add function in JavaScript it will return 23.

You may encounter this issue when you receive input from the user and expect a number but it's returning a value in string format. For example, if you pass "2" and "3" to the above add function in JavaScript, it will return 23.

Let's write a function to understand more.

const concatenateAndConvertToUppercase = (a: string, b: string) => {
    let uppercaseA = a.toUpperCase();
    let uppercaseB = b.toUpperCase();
    return uppercaseA + uppercaseB;
};

console.log(concatenateAndConvertToUppercase('hello', 'world'));

In addition, when you assign a type to a variable or argument, your IDE shows related methods for that type.

The example above shows that the variables a and b have been assigned the type string. The IDE picks it up and displays all the methods a string can have as follows:

image.png

This is why type assignments are important as they prevent runtime errors, unpredictable behavior, and speed up the development process.

CONFIGURE TYPESCRIPT:

In a real-world project, when you are using TypeScript with something like React or Angular, you will have a tsconfig.json file that you can use to set up TypeScript compilation rules.

tsconfig.json file is an indicator that the directory is the root of the TypeScript project.

Run the following command to initialize a tsconfog.json file:

tsc --init

It will create a tsconfig.json file in the root directory with some default options.

If you remember we were running tsc index.ts -w to compile our index.ts into index.js, which means we can only compile one file at a time, which is not feasible.

Therefore, once you have added tsconfig.json you can run the following command, which will compile all the .ts files into equivalent .js files.

tsc -w

To test this, add the app.ts file in the root folder and add the following code:

console.log("This is app.ts file");

Now, run tsc -w it will generate two files index.js and app.js.

UNDERSTANDING tsconfig.json:

What makes this new tsconfig.json stand out is how well documented all the options are. All the options are quite self-explanatory. Despite this, you may not have to use all of these options for most projects.

Let's take a look at the most important and widely used options:

  • target: This tells TypeScript the version of JavaScript it should compile into. By default, it is set to JS version ES2016, which means that TypeScript code will be compiled into JS version ES2016.

  • lib: It provides libraries that we want to make available to TypeScript globally. It is commented by default and contains some default values. DOM, ES2016, DOM.Iterable, and ScriptHost are the default libraries. When you uncomment that and check out index.ts, it will throw an error Cannot find name 'console' since the DOM is not included in the library.

  • jsx: This is related to ReactJs. Controls how JSX constructs are emitted in JavaScript files.
  • experimentalDecorators: This will allow the use of decorators in your TypeScript file. We will take a look into what decorators are and how to use them in future blogs.

  • sourceMap: It helps us in debugging because it creates a .js.map file. It is a bridge by which you can debug your TypeScript files in the browser's dev tools.

  • allowJs: If you enable this the JavaScript files will also get compiled along with TypeScript files.
  • rootDir: As the name suggests, it shows the path to your root folder or where your TypeScript files are located.
  • outDir: It shows where you want to keep your compiled JavaScript files. Currently, after compilation, our .ts and .js files are getting stored in the root directory. Let's configure outDir to understand the concept.

Uncomment outDir from tsconfig.json:

...
"outDir": "./dist", 
...

Now delete index.js and app.js files from the root directory and run the following command:

tsc -w

The dist folder will be created in the root directory. This folder will contain all of your .js files as you can see in the following image.

image.png

To get the output on the browser, we need to update index.html to match the new location of .js files. Change the index.html file as follows:

...
 <body>
    <div id="root">Hello....</div>
    <script src="./dist/index.js"></script>
  </body>
...
  • removeComments: This will remove all the comments from compiled .js files that you have added in .ts files
  • noEmit: It will restrict generation of compiled .js files.
  • noEmitOnError: This will avoid generating compiled .js files if your .ts file has an error in it.

  • strict: It enables all strict type-checking options. If you set this to false you will lose all the powers of TypeScript.

  • noImplicitAny: This shows an error when we don't give a type to unassigned parameters. Let's see an example:

Take a look at the following image:

image.png

There is no type assigned to the data parameter in the above code, which could result in unexpected behavior if the code is complex.

  • strictNullChecks: It tells TypeScript that shows a warning when any value which possibly is null. Let's take an example:

In index.html add button tag with id my-btn:

...
 <body>
    <div id="root">
      <button id="my-btn">Click me</button>
    </div>
    <script src="./dist/index.js"></script>
  </body>
...

Now, let's access this button in index.ts file:

let btn = document.getElementById('my-btn');

btn.addEventListener('click', () => {
  console.log('Clicked');
});

If you notice TypeScript will throw an error for Object is possibly null, that means the btn variable might be null, and you could receive a runtime error saying Cannot read property addEventListener of "null".

We know as a developer that button with id my-btn exists. To make the above code work, you have to do the following:

let btn = document.getElementById("my-btn")! as HTMLButtonElement;

btn.addEventListener("click", () => {
  console.log("Clicked");
});

In this case, we are telling TypeScript that you will get a button with the id my-btn. Consider this variable as an HTMLButtonElement. As we will discover in future blogs, this is called "type casting".

  • noUnusedLocals: This option will show a warning if any unused variables are declared but never used.

  • noUnusedParameters: This option will show a warning if any unused function parameters are declared but never used.

  • noImplicitReturns: TypeScript will throw an error if your function has a conditional return. Take a look at the following code:

image.png

If you are returning anything, you must return a value after the conditional return statement. Therefore, you need to add a return outside the if block as follows:

image.png

Other options are a bit on the advanced side and need more knowledge about TypeScript. We will cover those in future blogs.

CONCLUSION:

  • TypeScript brings a lot of benefits to our productivity and developer experience. It is not unique to Angular, other powerful frontend frameworks such as React and Vue are starting to be used with TypeScript to allow developer teams to create applications that are reliable, sustainable, and scalable.

  • JavaScript and TypeScript are continually evolving but not competing against each other. TypeScript was created to complement and enhance JavaScript - not replace it. The future may see them becoming very similar in features but with TypeScript remaining the statically-typed alternative.

  • With this TypeScript introduction, we’ve just scratched the surface of all the amazing things that we can do with TypeScript.

Also, Make sure to subscribe to our newsletter on https://blog.learncodeonline.in/ and never miss any upcoming articles related to TypeScript and programming just like this one.

I hope this post will help you in your journey. Keep learning!

My Website, connect with me on LinkedIn and GitHub .

Did you find this article valuable?

Support Learn Code Online by becoming a sponsor. Any amount is appreciated!