First, go to https://www.typescriptlang.org/
and download typescript and install it on your system. The download section of the site can be accessed at this link: https://www.typescriptlang.org/#download-links
Installing typescript using npm
is the easiest way, so that's what I do. Note that if you do not have node.js
installed, npm
commands will not be executed for you, so be sure to install it. Now simply open your terminal and type and run the following code in it:
npm install -g typescript
TypeScript is installed for you. In this step, I create another file called using-ts.ts
(note that the extension is ts
, not js
). Then I paste my JavaScript codes in it:
As you can see I got several errors quickly. The errors I get from our constant names (button
, input1
, and input2
) are because my javascript file (js-only.js
) is open. Typescript recognizes that there are two variables with two identical names in these two files and issues you an error. To solve this problem, I simply close the js-only.js
window and these errors disappear:
As you can see in the image above, now the only remaining errors are related to value
s. Typescript detects that our code has a problem:
We have taken the HTML elements and put them inside constants. Then we have called the value statement on these constants. TypeScript says that the value
may not exist for the element we received. Some HTML elements have a value
(for example, input
s), but not all HTML elements have a value
, and this code does not specify this explicitly.
To solve the problem, we must specify that yes our constant is not null
:
const input1 = document.getElementById("num1")!;
By placing the sign !
In front of this code, we tell Typescript that this code will never be null
and we are sure of our work. We should also tell it that the element we receive in this section is an input
, so it will definitely have a value
:
const input1 = document.getElementById("num1")! as HTMLInputElement;
Naturally, the above code does not work in a JavaScript file in js
format and must be written in a file in ts format. I do the same for the second input
.
In the next step, we will learn about the type feature in TypeScript. When I say type, I mean data type, that is, the type of data (string, number, etc.). In TypeScript, you can specify the type of data explicitly, and you have many more types than JavaScript. Look at the image below:
As you can see, under num1
and num2
, a three-point mark is created, which is actually a typescript warning to us. If you move your mouse over this symbol, the typescript will tell you that the default type for num1
and num2
is any
type, which means it can take any value, although the typescript itself tries to guess based on the codes that the type What is the best data in this section? In fact, TypeScript says that we must also specify the data type for these two inputs.
We can do this like this:
function add(num1: number, num2: number) {
return num1 + num2;
}
It means adding a colon and then writing the desired type. Now, by adding the desired type, we get another error:
As you can see, input1.value
has an error. why Because we said that the first parameter must be a number
, but the value received from the browser is always a string
. Before I fix this error, I want to show you how to compile TypeScript code to JavaScript:
tsc filename.ts
To convert typescript files to javascript, you first specify the tsc
command and then the name of your typescript file. By executing this command, a JavaScript file with the same name will be created in your folder. You must use the same JavaScript file in your browser (as usual in script
tags). For example, for me:
tsc using-ts.ts
As you can see, since I had not solved the error in the typescript file, I get an error by compiling the codes in the visual studio code terminal. Of course, as shown in the image above (left), the JavaScript file (using-ts.js
) is still created and given to me. Of course, later we can override the typescript settings so that the javascript file will not be compiled if there is an error.
To solve this error, it is enough to add a +
sign to our arguments:
button.addEventListener("click", function() {
console.log(add(+input1.value, +input2.value));
});
The +
sign is not specific to TypeScript and is a JavaScript statement. This symbol converts a value
to a number
. As soon as we change the code like this, all the errors disappear. Now I run the command tsc using-ts.ts
again and this time the javascript file is delivered to me without error.
So the content of my typescript file was as follows:
const button = document.querySelector("button");
const input1 = document.getElementById("num1")! as HTMLInputElement;
const input2 = document.getElementById("num2")! as HTMLInputElement;
function add(num1: number, num2: number) {
return num1 + num2;
}
button.addEventListener("click", function() {
console.log(add(+input1.value, +input2.value));
});
But the contents of my compiled JavaScript file are as follows:
const button = document.querySelector("button");
const input1 = document.getElementById("num1");
const input2 = document.getElementById("num2");
function add(num1, num2) {
return num1 + num2;
}
button.addEventListener("click", function () {
console.log(add(+input1.value, +input2.value));
});
As you can see, the commands that were specific to typescript are finally removed from the javascript file! This was a simple example of the power of TypeScript, imagine how much these capabilities will help us reduce code errors in real projects!
Note that adding the ts
file to the browser will break the code because browsers cannot execute typescript files:
<script src="using-ts.ts" defer></script>
So the correct way to add the file is to run the command tsc filename.ts
and give the browser the compiled JavaScript file (extension js
):
<script src="using-ts.js" defer></script>
Now, if we go to the browser and test the codes, instead of the number 105, we get the same number 15. This is just one example of hundreds of examples of the power of TypeScript.
Congratulations @albro! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
Your next target is to reach 3000 upvotes.
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.
Hello,
this Comment has been upvoted with 100%, thanks to @albro who burned 1000 PLANET
With this burn @albro is actively participating in the CLEAN PLANET reward protocol.
@albro is helping @cleanplanet to grow with the curation.
Thanks for your help
@cleanplanet