Home > Web Front-end > JS Tutorial > TypeScript for Beginners, Part 1: Getting Started

TypeScript for Beginners, Part 1: Getting Started

William Shakespeare
Release: 2025-03-17 09:15:18
Original
825 people have browsed it

Let's start this tutorial with the question: "What is TypeScript?"

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. As an analogy, if JavaScript were CSS, then TypeScript would be SCSS.

All the valid JavaScript code that you write is also valid TypeScript code. However, with TypeScript, you get to use static typing and the latest features that get compiled to plain JavaScript, which is supported by all browsers. TypeScript is aimed at solving the problem of making JavaScript scaleable, and it does a pretty good job.

In this tutorial, you will begin by reading about the different features of TypeScript and why learning it is a good idea. The rest of the sections in the article will cover the installation and compilation of TypeScript, along with some popular text editors that offer you support for the TypeScript syntax and other important features.

Why Do We Need TypeScript?

We use programming languages to instruct computers how we want them to do something. They basically act as a medium of communication. However, computers don't directly understand the JavaScript, PHP, or Python code that we write. All the human-readable code that we write is ultimately converted to machine code which the computers can run and understand.

Modern programming languages are written with the needs of the programmer in mind. This means that different programming languages are designed with different feature sets due to the way they are meant to be used. JavaScript was written to make it very easy to get things done by writing a minimal amount of code.

JavaScript has become a lot more popular since its early days and is now widely used for small- and large-scale projects. Some limitations of JavaScript that were acceptable when writing small programs can hamper productivity when working on large projects with many team members.

TypeScript was created to address these limitations by adding a variety of features like type-checking to help you quickly catch any errors that might crop up when making changes to code in large-scale projects.

Why Learn TypeScript?

If you have never used TypeScript before, you might be wondering why you should bother about learning it at all when it compiles to JavaScript in the end.

Let me assure you that you won't have to spend a lot of time learning TypeScript. Both TypeScript and JavaScript have very similar syntax, and you can just rename your const keyword to specify that we want to prevent any changes to the value of that variable through reassignment or prevent its re-declaration. However, this doesn't mean that the value of the variable is immutable. There are still other ways to change it. Here is an example:

const fruits = ["Apples", "Mangoes", "Bananas"];<br>const vegetables = ["Potatoes", "Onions", "Cucumbers"];<br><br>fruits.push("Orange");<br>// ["Apples", "Mangoes", "Bananas", "Orange"]<br><br>fruits[0] = "Papayas";<br>// ["Papayas", "Mangoes", "Bananas", "Orange"]<br><br>fruits = vegetables // Error<br>
Copy after login

Up to the last line, the above code is perfectly valid JavaScript and won't throw any errors. We declared undefined as a value. This approach makes sense because it allows us to dynamically add, remove, or update an object's properties. However, it can also be a source of errors or unexpected behavior. Here is an example:

let guy = {<br>    name: 'Mario',<br>    age: 56<br>}<br><br>console.log(guy.name   ' is '   guy.ahe   ' years old.');<br>// Mario is undefined years old.<br>
Copy after login

Mistyping ahe is not considered an error in JavaScript, but it would have been caught in TypeScript. Try compiling the above code from TypeScript to JavaScript, and you will see an error about perimeterTriangle(). This results in a nonsensical value being output as the perimeter of our triangle.

function perimeterTriangle(a, b, c) {<br>    console.log(`Perimeter of the triangle is: ${a   b   c}`);<br>}<br><br>perimeterTriangle(20, 30, "Potato");<br>// Perimeter of the triangle is: 50Potato<br><br>perimeterTriangle("Potato", 10);<br>// Perimeter of the triangle is: Potato10undefined<br><br>perimeterTriangle();<br>// Perimeter of the triangle is: NaN<br><br>perimeterTriangle(20, 30, 50);<br>// Perimeter of the triangle is: 100<br>
Copy after login

Even if you don't make any changes to the above code and try to compile it from TypeScript to JavaScript, you will still get errors with the second and third function calls due to a mismatch in the number of arguments provided. However, we can add more information to our function definition by specifying the type of arguments that we expect the function perimeterTriangle() to accept.

function perimeterTriangle(a: number, b: number, c: number) {<br>    console.log(`Perimeter of the triangle is: ${a   b   c}`);<br>}<br><br>perimeterTriangle(20, 30, "Potato");<br>// Error: Argument of type string not assignable to type number.<br><br>perimeterTriangle("Potato", 10);<br>// Error: Expected three arguments but got 2.<br><br>perimeterTriangle();<br>// Error: Expected three arguments but got 0.<br><br>perimeterTriangle(20, 30, 50);<br>// Perimeter of the triangle is 100.<br>
Copy after login

Now, even the first function call throws an error due to the mismatch in argument type. TypeScript will help you catch many such errors and save a lot of time in the long run.

Compiling TypeScript to JavaScript

Let's say you have written some TypeScript code in a .ts file. Browsers won't be able to run this code by themselves. You will have to compile the TypeScript into plain JavaScript that can be understood by browsers.

If are using an IDE, the code can be compiled to JavaScript in the IDE itself. For example, Visual Studio allows you to directly compile the TypeScript code to JavaScript. You will have to create a tsconfig.json file where you specify all the configuration options for compiling your TypeScript file to JavaScript.

The most beginner-friendly approach when you are not working on a large project is to use the terminal itself. First, you have to move to the location of the TypeScript file in the terminal and then run the following command.

tsc first.ts<br>
Copy after login

This will create a new file named first.js in the same location. Keep in mind that if you already had a file named first.js, it would be overwritten.

If you want to compile all the files inside the current directory, you can do so with the help of wildcards. Remember that this will not work recursively.

tsc *.ts<br>
Copy after login

Finally, you can only compile some specific files by explicitly providing their names in a single line. In such cases, JavaScript files will be created with corresponding file names.

tsc first.ts product.ts bot.ts<br>
Copy after login

Let's take a look at the following program, which multiplies two numbers in TypeScript.

let a: number = 12;<br>let b: number = 17;<br><br>function showProduct(first: number, second: number): void {<br>    console.log("The product is: "    first * second);<br>}<br><br>showProduct(a, b);<br>
Copy after login

The TypeScript code above compiles to the following JavaScript code when the targeted version is set to ES6. Note how all the type information that you provided in TypeScript is now gone after the compilation. In other words, the code gets compiled to JavaScript that can be understood by the browser, but you get to do the development in a much better environment which can help you in catching a lot of bugs.

let a = 12;<br>let b = 17;<br>function showProduct(first, second) {<br>    console.log("The product is: "   first * second);<br>}<br>showProduct(a, b);<br>
Copy after login

In the above code, we have specified the type of variables a and b as numbers. This means that if later you try to set the value of b to a string like "apple", TypeScript will show you an error that "apple" is not assignable to the type number. Your code will still compile to JavaScript, but this error message will let you know that you made a mistake and help you avoid a problem during runtime.

Here is a screenshot that shows the error message in Visual Studio Code:

TypeScript for Beginners, Part 1: Getting Started

The above example shows how TypeScript keeps giving you hints about possible errors in code. This was a very basic example, but when you are creating very large programs, messages like these go a long way in helping you write robust code with less chance of error.

Final Thoughts

This getting started tutorial in the series was meant to give you a very brief overview of different TypeScript features and help you install the language along with some suggestions for IDEs and text editors that you can use for development. The next section covered different ways of compiling your TypeScript code to JavaScript and showed you how TypeScript can help you avoid some common errors.

I hope you liked this tutorial. The next tutorial of the series will discuss different variable types available in TypeScript.

The above is the detailed content of TypeScript for Beginners, Part 1: Getting Started. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template