Skip to content
HackAndStuff

TypeScript Tutorial for Beginners

Programming3 min read

Typescript

What is TypeScript ?

TypeScript is just a typed superset of JavaScript . It has all features of plain old JavaScript and on top of those, it provides its own set of features. Every TypeScript file compiles down to plain JavaScript. It is open- source and was created by Microsoft to help developers collaborate easily and develop large scale projects. It is not a new language! Put simply , it is just the Javascript you know ,with the new cool ECMAScript features .

TypeScript has features like static typing and type inference which makes debugging your code easy and also helps to reduce those silly runtime errors we often get in JavaScript. It also has many cool features including interfaces, inbuilt support for Object Oriented Programming, and a lot more. To make it more cool , it has a great IDE support , which means we get intellisense , auto-complete , the red line instead of a runtime error and much more.

It is totally upto you , if you want to use TypeScript or not . I am not trying to convince you to use TypeScript instead of JavaScript. But if you have decided to go with it , let us just get to the cool part ... CODEEEEE!!!

The Cool Part : Code

Ok! Let's start with the setup . Make sure you have node installed on your machine . Type

1node -v

to verify that and you should see your installed node version . If not , first go and install node for your OS.

Now to install typescript , run

1npm install -g typescript

which will install typescript globally . If this is successful , you should now have access to the TypeScript compiler which you can check by running

1tsc -v

Create a file , main.ts and type some simple familiar JavaScript stuff.

1function hello(name) {
2 console.log(`Hey ${name}`);
3}
4
5hello("Reader");

Compile it using the tsc by running tsc main.ts and you will see , it generates a corresponding main.js file . You can run the generated main.js by node main.js . It is that simple !!

Types in TypeScript

As TypeScript is a typed language , we can declare the types of variable during declaration which makes the code more readable and reliable. Types can be categorized in three parts here -

  • Any
  • Built-in
  • User-defined

The any type as the name suggests , is the most flexible type available , and it can contain any type of variable . The Built-in types are types which Typescript gives you like number, string, boolean, undefined, null, and void. The user-defined types include enum, array, interface, class, and tuple.

So unlike JavaScript which is dynamically typed , we can declare variables here in the following way

1let name:string = 'Bruh';

A colon followed by the type of the variable. If you want to dive deep into types, you can have a look here .

Commenting

We use the same syntax for commenting as we are used to in JavaScript , double slash for a single line comment and /* */ for a multiline comment.

1let num: number = 1; // This is a single line comment
2
3/* This is a
4multi-line comment
5*/
6
7let name: string = "elliot";

Functions

A function in TypeScript is fundamentally the same as we do in JavaScript , but it comes with a lot of additional features here.

A simple function in TypeScript looks like

1function add(a: number, b: number) {
2 let c = a + b;
3 console.log(`Here is your result ${c}`);
4}

But in TypeScript , we can do things like passing Optional Parameters , default parameters and anonymous functions. For making a parameter optional , we append the name of the parameter with a ? like (name?:string). If we don't pass the optional parameter , it is set to undefined.

In TypeScript , functions can be introduced in two ways in code , either as a function declaration or as an expression . What we did above was a function declaration . There isn't much difference among these though , put simply, when a function comes as a part of a statement, it just becomes a Function Expression.

Object Oriented

TypeScript is Object Oriented unlike JavaScript which supports OOP. We can define classes in TypeScript using the class keyword. Let us see a simple class in TypeScript.

1class Car {
2 model: string; // this is a field
3
4 //constructor
5 constructor(model: string) {
6 this.model = model;
7 }
8
9 //function
10 getModel(): void {
11 console.log("The model of the car is : " + this.model);
12 }
13}

To create an object of this class , we can simply use the new keyword

1let car = new Car("Model 1")

Type Assertions

There are two ways to for explicitly asserting type of a variable in TypeScript.

As Keyword

1let name
2name='Elliot'
3// Now the name has the type _any_ and we cannot use the awesome string operations on it
4// So to cast it as string we use as
5let lowerName=(name as string).toLowerCase()
6console.log(lowerName)

<> operator

1let lowerName=(<string>name).toLowerCase()

Type Checking

If we ever run into a situation , where we need to be certain that a variable is of certain type , we can take the following two approaches.

instanceof

1class Person {
2 name: string;
3
4 constructor(data: string) {
5 this.name = data;
6 }
7}
8
9let obj = new Person("Elliot");
10if (obj instanceof Person) {
11 console.log("Yeah it is!");
12}

typeof

1let age = 12;
2console.log(typeof age);

Union Types

Ok. This is really cool . You can declare a variable to be of multiple types using the pipe ( | ) operator. You can just combine two or more types by syntax like type1|type2|type3 . Let me show you what I mean.

1let stuff: number | string;
2stuff = "jatin";
3console.log(`typeof stuff is ${typeof stuff} and value is ${stuff}`);
4stuff = 14;
5console.log(`typeof stuff is ${typeof stuff} and value is ${stuff}`);

Wrap It Up

So, this was just a brief insight into what TypeScript can do and how you guys can get started with it. Obviously, we have just scratched the surface here. There is a whole lot of other cool things like namespaces, modules, interfaces and what not, that TypeScript provides us and hopefully , we will cover that in another cool blog post. I hope this helped you to learn something new . That being said ,

Stay curious and as always

See ya later!

© 2021 by Jatin Malik. All rights reserved.