Typescript for JS developers

Typescript for JS developers

Wait , what is typescript?

According to the makers of typescript,

TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale . TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor.

Now I understand that its all theory and hard to relate to what they have actually meant here . Don't worry , we are going to discuss an example shortly .
But for now , lets keep these points in mind:

  1. Its built on top of JS , so we can see it as a superset of JS .

  2. It implements static typing ( we will discuss what do we mean by it ) .

  3. It makes JS more strict .

Can you please explain the points?

Okay first lets look into this Java code.

First things first , we know that we need to declare variables with their types in Java and accordingly assign them values based on their types .
So here when we declared "a" to be "int" , we need its value to be an integer and not a string. And hence we got an error when we tried to assign a string to it .
This is static typing where a type checking occurs during compile time .

Now lets have a look at JS code:

If you see here , we initially used "a" to store integer but later we changed its value to a string . Hence JS is said to be a dynamically typed language where we can change the type of variables by assigning them values of different types throughout the program .

Problem : in large codebases it might become a problem if we assign wrong values . It might also break our code . For example your backend server might break if you lets say send a string for a property which in the mongoose schema is directed to receive a number .

Solution: we introduce types in JS.

Now lets have a look at this (typescript) TS code:

Nothing fancy here , as I said TS is built on JS . What we did is give a type to variable "a" , which is basically "number" here . Now TS helps in detecting such errors where wrong types are used like here it marks that "a" is supposed to be a number and not a string . For now it will compile but it can be made further strict by asking it to throw compilation errors as well on such occasions.

Okay so what about functions ?

I hope you can understand whatever is discussed till now . Don't worry , take some time to marinate and continue . You can go to Replit or CodeSandBox and try running them yourselves and I am sure you would be able to understand them .
Now lets look into how we can use types in functions.
So for that lets devise some code to make a calculator which would do the four basic arithmetic operations.

You can see the basic JS code , how we added types to it to convert it to TS code and then simply called it and displayed it in the logs. You can also understand about the types in the declaration explanation.

Now if you try to give some value of the wrong type , TS will get annoyed.

But now lets move little bit deeper . We see that "operation" can't be some random string rather it should be either "sum" , "sub" , "mul" or "div" so it wouldn't hurt to be more specific about it , right ?

Here we have specified the possible values of operation , failing which TS will get angry.

So what does TS compiler ( tsc ) actually do?

It only checks whether the types are being satisfied or not and then simply converts the TS file to JS file. It is JS engine which is actually going to run the code.

Lets dive deeper into it.

Open a local folder using your favourite code editor . Now install typescript compiler globally using this command:

npm install -g tsc

I have already done that in my local folder which I opened using VS Code . I can show you the version here .

Now we are going to use "tsc index.ts" so that typescript compiler converts the index.ts file into its equivalent .js file . In your local folder , add the same index.ts file which is shown above and then in the terminal run the command below and see the magic happen !

tsc index.ts

You would be able to see an index.js file generated in your folder.

Lets have a look at the .js file.

As you can see , our main JS code is present as expected ( alongwith the comments ) .
Now we are going to discuss about tsconfig.json.

What is tsconfig.json file?

So lets first generate the initial tsconfig.json file in our working directory.

Run the below command :

tsc --init

You can see a tsconfig.json file

Lets clean it up a little bit.

"target" property's value determines the current ECMAScript version to be used (basically how the JS code should look ).

"module" determines the way we would be exporting the code. Like here its value is "commonjs" . We could also set it to "esnext" , "es2022" and so on . You could google what are the different ways to import and export functions in JS . Since our current discussion is not centred around it , I am not discussing it here .

Okay I get the basic stuff , can we see something advanced now?

Interfaces

I see , lets try to get into advanced stuff like interfaces , types and enums but before that , why don't we try to give types to an object? Seems interesting , right ? Lets see the code.

If you look carefully , we are basically trying to send an object to a function ( you can see the plain JS code ) and we need to be careful about what we are sending . So we added the type to "report" based on what needs to be sent. For executing you can simply run "tsc index.ts" to get the .js code and then run it using "node index.js" .

But now a problem can arise where a similar type is used more than once . Have a look at the below code:

You can see that the types are getting redundant . To solve this problem we can use interfaces . Have a look at below code:

As you can see , interfaces can so easily solve this problem . Its like storing the object type in a variable and using it again and again.

Okay so we got a gist of what an interface can do . Lets look at some of its properties .

Interfaces can use other interfaces

So what do we mean by it ? Lets have a look at the code .

If we would have written the "report" types all over again in "JobApplication" interface it would have been redundant . To solve that , we simply used a predefined "Report" interface . As programs become big , there could be further necessary complications like inside "Report" , there could be another predefined interface being used .
Okay now lets move to the next property .

Interfaces can extend other interfaces.

Now this is kinda similar to the previous point but lets have a look .

Here the types of "Report" are just getting copied to "Job Application" since it is extending the "Report" interface . You can see their application in the function definitions .

So that basically sums up interfaces for now . It can also be used in classes but for now lets leave it for another day .

So lets recap the basics of interfaces:

1.It can be used to describe the type of objects .

2.Interfaces can use and extend other interfaces .

3.Interfaces can be implemented in classes (lets leave it for now) .

One final point: we can make properties optional in interfaces . Lets see what I mean by this .

The "?" makes the property optional .

Okay lets move to another similar topic called "Types".

Types

It is quite similar to interfaces but has its own advantages.

Lets have a look.

I hope you got to know little bit about how Types can be implemented . Type is more or less similar to an interface . It uses equation in its syntax . But Types cannot extend other Types .

But what could be its additional benefit over interfaces ? Well Types can be used for the union of interfaces .

Lets see the problem first:

As we can see it would be really nice if we could combine the interfaces by OR under another "something" and then use it again and again to avoid redundancy .

And that "something" is "Type". It can be used to combine interfaces using OR or AND.

Lets see its use in the previous example:

I think now we are able to understand what is its usage and how we can implement it .

I guess its time to move to the last topic of the day : Enums ! Yep , its almost over , just a little patience . So drink a glass of water for the final fight !

Enums

They are mainly used to represent a fixed set of values . Thats it ? Well not really but we will need to look at some code first .

Here we have tried to recreate the arithmetic calculator using enums . So we have assigned named values "Add" , "Sub" ,"Mul" and "Div" under enum . Accordingly if we assign the type and when passing if we want to pass "Add" , we pass Arithmetic2.Add .

Now one important thing to note here is when we are trying to access the value of "type" why are we using 0 ,1 , 2 ... ? Its because internally the enum's contents are looking like this : Arithmetic2.Add=0 , Arithmetic2.Sub=1 , Arithmetic2.Mul=2 and Arithmetic2.Div=3 . So when we are passing Arithmetic2.Add , we are actually passing 0 and hence in the console , you can see the result 8.

So ... that's it ! Its great that you came this far and should congratulate yourself . Now take some time and try to marinate this entire page again . For practice , you can try converting your existing JS codes to TS codes .

Is it finally over ?

Nope , not at all . Rather this is just the beginning . I will keep learning more about typescript and would produce more such blogs . Till then , Thank you !