Close
Close full mode
logoWebDevAssist

Introduction to TypeScript

Introduction to TypeScript:

In this post, I will give you an introduction to TypeScript. You will learn what is typescript and why we use it.

I have published one vieo on TypeScript. You can watch it here:

What is typescript:

TypeScript is:

  • Open-source language by Microsoft
  • It is built on JavaScript. It is a superset of JavaScript.
  • We can use JavaScript with TypeScript.
  • It supports all features of JavaScript.
  • You can easily migrate one JavaScript project to TypeScript.

Why should we use TypeScript:

TypeScript has many advantages, like:

  • It provides static type checking. It means, we can find out all the type errors without running the program.
  • It provides all object oriented programming features. We can follow OOP easily with TypeScript.
  • We can use type using TypeScript. That is, we can say if a variable is number or string etc. This makes the code readable and clean.
  • It is easy to learn. If you already know JavaScript, you can easily learn TypeScript.
  • It is easy to migrate an existing project to TypeScript. Most popular JavaScript framework provides supports for TypeScript.

Example program:

Let's try to understand it with an example. Let's take a look at the below program:

function findSum(first, second) {
console.log(first.length + second.length);
}
findSum("hello", "world");

This is a JavaScript program that finds the sum of lengths of two strings using the findSum function.

It will work. But, if I pass one number,

findSum("hello", 12)

It will print this as NaN. This is because, we don't have any length property for numbers.

Converting the program to TypeScript:

Let me convert the above program to TypeScript. It will be:

function findSum(first: string, second: string) : void {
console.log(first.length + second.length);
}
findSum("hello", "world");

Here, we have defined the type for first and second arguments as string. The function doesn't return anything. So, we have written the return type as void.

Now, if you try to call findSum with anything other than strings, it will show one error.

Where to test TypeScript programs:

You might be wondering how to test the above program. You can run TypeScript in your own machine or you can use the official online compiler. Go to this website, write any code in the left side code editor, and click on Run. It will show the console.log messages on the right side Logs window.

Typescript online
Typescript online

Another way is to by downloading typescript on your system. This I will show you in a different post.

Subscribe to our Newsletter

Typescript for beginners — Previous
Typescript Tutorials for beginners
Next
How to install TypeScript