https://anuragdeep.com/

https://anuragdeep.com/

TypeScript: what is it, and why should a programmer learn it?

TypeScript Nov 30, 2022

JavaScript is one of the most widely used programming languages among programmers. Its code should work correctly in any predictable situation. Otherwise, the site's or application's entire functionality will be compromised. To avoid this, the code contains a large number of checks and/or extensive comments. However, in the first case, everything becomes too complicated, and in the second case, it is still impossible to protect against errors.

Various JavaScript add-ons, like TypeScript, should solve these problems and at the same time add stability to the code. Including in unforeseen situations.

What is typescript

TypeScript is a standalone programming language based on JavaScript, so it should be seen as more of an add-on for better JS work than a completely independent language. Differs from its progenitor in strong typing. The first versions of TypeScript appeared in 2012. It is constantly being improved - the current current version is 4.6.3 from 2022.

TypeScript itself consists of three parts:

  • basic programming language syntax;
  • code compiler;
  • code editor.

TypeScript originated as a solution to the shortcomings of JavaScript that can appear in large applications. Developing complex programs required lightening the syntax and logic of standard JavaScript to make them more stable and easier to maintain. Plus, large JS applications often started to slow down due to the abundance of code that could be tried to be excluded from the program. Microsoft suffered the most from problems like this, which is why they created the first versions of TypeScript.

The solution to a problem can be elegantly expressed in .ts or .tsx files thanks to TypeScript's simplified syntax. It is fully compatible with JavaScript applications, so any JS program will be syntactically correct for TypeScript (and vice versa).

The compiler built into TypeScript helps to detect a significant part of defects, logical errors in the code even before the project is uploaded to production. His job is to convert the original TypeScript into JavaScript. After that, the program is analyzed in order to find problem areas. It is noteworthy that TSC can create JS files of any, even the earliest versions. The developer can flexibly customize the conditions for checking and parsing TypeScript.

It is noteworthy that with the help of TypeScript it is possible to detect even minor defects that are not technically errors. However, if functionality is added to the project or other changes are made, there is a risk that such problems may manifest themselves, requiring additional changes.

An example of using TypeScript checks

Often, a try catch statement is used to check code for errors in JavaScript. Inside it, a message is generated with information about the detected error. It is noteworthy that the message can take any type - a string, a number, or even an object. This approach does not always allow you to immediately determine the error and the degree of its criticality. For example, the information in the Error type block does not always contain error data. The developer is often left to rely on experience and guesswork, which slows down the work on the entire project.

The TypeScript compiler, by default, independently checks the catch value for errors it finds. Here is an example of the conditions for such a check:

catch(err){
	console.log(err.message)
}

If the console displays the number 42 next to the err item, it means that an error was detected during the check. You can disable the compiler's automatic checking of the contents of the catch block.

The compiler provides the useUnknownInCatchVariables flag, which disables catch checks. Often used to prevent a program from crashing. The fact is that if some errors are detected during automatic testing, the program may close. In such cases, the developer will have to find and fix such critical failures himself.

TypeScript support by code editors

Most common code editors support TypeScript. These include VS Code, Atom, WebStorm, SublimeText. There is also an online TS Playground code editor designed to introduce and learn TSC. It will not work to write full-fledged projects on it. The sandbox has limited ability to run the resulting JavaScript. However, you can include modules from npm in your code, examine the purpose of the compiler flags, examine the resulting JavaScript and the text of the module definition (.d.ts).

Editors that have TypeScript support are often able to do automatic code analysis, point out errors to the developer, and give notes. You can also set up automatic abbreviations and/or replacements.

Reasons to move to TypeScript

Now this language is used in large projects. For example, the VS Code editor that most developers work on is written in TS. Angular technology is also written on it, which is also very popular among web developers. TypeScript is developed and maintained by Microsoft. In addition, there are other, more serious reasons to start learning TS.

Reason 1: Easy to learn

If you are already familiar with JavaScript syntax and have previously completed projects using it, then learning and further using TypeScript will not be difficult for you. Their syntax is very similar, with a few exceptions. They are clearly written about in the documentation, plus, there is a community of its own that will help in complex issues. Unfortunately, there is not much information in Russian yet, so for comfortable learning TypeScript it is desirable to know English at an acceptable level.

Reason 2: Fewer Unit Tests Used

For correctly working JS code, if we are talking about a large project, you need to regularly write unit tests. Otherwise, you may not find any error. Approximately 10-20% of the JS code of a large project is all kinds of tests. Naturally, it takes even more time to write them, as a percentage of the time spent on development.

function addition(a, b) {
    if (typeof a != 'number' || typeof b != 'number') {
        return a + b;
    } else {
        Throw(...)
    }
}

Writing conditions for validation in JavaScript makes the code more cumbersome and increases the writing time.

Another JavaScript problem that makes testing more difficult is the presence of strong data typing. In unit tests, you need to be sure that the function shows the correct information, discarding undefined arguments, data without values, strings, and similar “garbage”. In TypeScript, not only are some tests built into the language itself, it also makes it easier for you to work with data types. For example, you can specify not only explicitly the numeric type a, b to the result, but also their values ​​as nullable.

Reason 3: Convenient TSC Toolkit

TSC stands for "TypeScript compiler". This is the simplest tool included in the programming language itself and works in any editor, regardless of the presence of TypeScript syntax support. The task of the tsc tool is to compile files with the .ts extension to the .js extension.

To get started with TypeScript, you need:

  • Open the terminal of your code editor. Enter and apply the npm install –global typescript command there. She is responsible for installing TypeScript on the system. If installation is required only in a specific project, and not the entire system, then simply remove the word “-global” from the command.
  • Create the first .ts file. You can “fill” it with any commands. For example, let's write a simple console.log.
  • In the terminal of your code editor, enter the tsc command to compile the file.

To explore all the possibilities of tsc, let's look at how to compile a file with incorrect syntax. Let's write the command shown in the screenshot below. It deliberately made a mistake in the argument, more precisely in its type - it is written as a string, not a number.

// test.tsc
let cos = Math.cos("0.5");

An example of a recorded command

When you try to compile, you will get a message about the incorrect type of the argument. This way, you can easily detect such errors when compiling ts-files to js. No additional tests or long self-checking of the written code is required for this.

Data type error message

Additionally, TypeScript provides many configurations to customize your workflow. An example of one of the flexible configurations in the screenshot below:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "experimentalDecorators": true,
    "noLib": false,
    "outDir": "./dist",
    "allowJs": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

Example of an advanced configuration file

By changing the true-false values, you can customize the TypeScript workbench for you. In addition to this configuration, you can add two more properties:

  • includes. It is responsible for automatically indicating the location of the sources, as well as prescribing the structure of the location of the output files. If you now put the file test.ts in the src/ folder, next to the other ts files, then running tsc with no arguments will give you a similar structure to the other files in the folder. It is possible to enable tracking and updating when files change. To do this, use tsc - watch;
  • exclude. Responsible for almost everything the same, but focuses more on output files. The properties specify where these files should be placed by default, for example, “dist”.

Reason 4: Better data typing

To give a variable a type, simply put a “:” after it and write the type you want, for example, string. If the variable gets data that does not belong to the specified type, then you will receive a notification about this. This will make it easier for you to track possible errors during the execution of the code or the interaction of a potential user with it. You can also specify the function type and return value.

let a : string = "hello";
a = 123; // breaks

Specifying the data type of a variable in TS

To simplify work with data typing, you can use the “strictNullChecks” property. Enable it in the configuration file by setting this property to true. After that, it will be possible to receive comments on each variable, depending on whether its value corresponds to the previously specified type.

In TypeScript, you can specify or not specify data types. The question is, how do you know when they need to be specified in advance and when not? You can often find the opinion that strong typing, by analogy with Java and C, is necessary when writing code in TypeScript. It's really a matter of personal preference and convenience. On the one hand, “total” typing allows you to avoid some errors, but on the other hand, it takes more time to write code, and can also lead to declarations in 3-4 lines. Plus, type declarations make the code harder to read by humans - too much information on one line.

Specifying types or not is purely personal preference. However, they are recommended anyway, at least for functions with return values. In this way, you can ensure that at least 80% of your code is protected from unexpected errors related to incorrect data types.

Reason 5: Convenient project separation

For each project, you can set your own TypeScript configuration, which simplifies your work. The fact is that the configuration file is not created globally for all TS projects on the computer, but only for a specific project, therefore, you can make adjustments to it without fear that they will somehow affect other projects.

During the execution of the npm install command, the @types folder is automatically created, which is located in the node_modules directory. It also creates a .d.ts file. This is where the detailed configuration settings for a specific project take place. The whole basic structure of the file is already generated. You just have to make the necessary changes to it.

Reason 6: Using advanced typing

In general, data types in TypeScript are the same as in other programming languages ​​- no new ones have been introduced. However, you can perform advanced operations with existing ones, which allows you to avoid some errors and make the code more convenient to work with.

You can create your own data type with your own conditions. For example, type interface. In it, specify the types that will be immediately applied to certain variables, for example, name, email, and so on. This example is shown in detail below.

interface IUser {
    name: string
    email: string
}

const yann: IUser = {
    name: "yann",
    email: "barack.obama@gmail.com"
} // OK

const house: IUser = {
    name: "Eden house",
    size: "Huge"
} // Breaks

Example of defining custom types

Another interesting feature is the combination of data types using the corresponding operator - “|”. An example of such a union:

let a : number | string

Here, the variable a is assigned the type of a number and a string at the same time. This approach is very convenient when both a number and a regular string can be assigned as a value for a variable. This eliminates the need to write additional conditions that would be necessary for correct operation.

Additionally, overload is supported.

The role of TypeScript in the work of a developer

The main task facing the TypeScript developers was to create a product that would help other developers learn and develop products for any systems based on JavaScript. It was important to ensure that the programmers were confident that their code would eventually run in a predictable way.

Making sure that there are no contradictions and inconsistencies during the execution of a program in TypeScript is easier than in JavaScript. First of all, this is possible due to more advanced work with types - you can set the type for any variable and get predictable results. Here is the whole list of useful tasks that TypeScript performs for the developer:

  • allows the developer to use a specific type for a particular variable;
  • controls the correctness of using the selected value of the variable, based on the previously assigned type;
  • reports errors in the use of operations, data assignment, directly in the code editor;
  • makes it possible to use OOP methodologies;
  • allows you to make modules of different formats;
  • allows you to customize the working environment for a specific project;
  • TypeScript integrates into environments such as Babel, Browserify, Grunt, Gulp, Jspm, MSBuild, NuGet, Rollup, Svelte Compiler, Vite, Webpack.

Conclusion

TypeScript makes life a lot easier for a developer doing large JavaScript projects. It should be understood that technology evolves, so your code must be scalable so that it can be easily customized to new customer requests. TypeScript does just that. However, it should only be considered in conjunction with JavaScript.

Tags

Anurag Deep

Logical by Mind, Creative by Heart