📜 ⬆️ ⬇️

TypeScript basics for developing Angular applications

TypeScript is a superset of JavaScript, that is, any JS code is correct from the point of view of TypeScript. However, TypeScript has some additional features that are not included in JavaScript. Among them are strict typing (that is, specifying the type of a variable when it is declared, which makes the code more predictable and easier to debug), mechanisms of object-oriented programming, and much more. Browsers do not support TypeScript directly, so the code on TS should be transported to JavaScript.

image

TypeScript is used to develop web applications using the popular Angular framework. In this article we will look at the basics of TypeScript, which are necessary in order to begin to master Angular and to work with it.

Preliminary preparation


Before using TypeScript, it must be installed:
')
sudo npm install -g typescript 

Now you can proceed to study the possibilities of the language. Open a text editor and create a new file. Put the following code in it:

 function log(message) { console(message); } let message = 'Hello Typescript'; log(message); 

Save it as main.ts and, going to the terminal where you saved it, run the following command:

 tsc main.ts 

This command creates a new file, main.js , which is a transpiled JS version of the main.ts file. This file can, for example, be executed using Node.js:

 node main.js 

Note that you do not need to tsc command when building the Angular application, since the ng serve tool will prepare the code for execution automatically.

TypeScript data types


TypeScript supports various data types. Among them are the following:

 let a: number      //: 1, 2, 3 let b: boolean     //: true, false let c: string      //: "abel agoi" let d: any         //        let e: number[]    // , : [1, 3, 54] let f: any[]       //   , : [1, "abel agoi", true] 

Please note that TypeScript supports another type, enum , you can read about it yourself.

Arrow functions


In JavaScript, functions are declared like this:

 let log = function (message) { console.dir(message); } 

In TypeScript, the same effect can be achieved by using arrow functions, which are declared using a sequence of characters => . Here's what it looks like:

 let log = (message) => { //     function console.dir(message); } //  ,     let log = (message) => console.dir(message); //      ,      let log = message => console.dir(message); //,     

Interfaces


It is not recommended to write functions that need to pass a lot of parameters. For example, it might look like this:

 let myFunction = ( a: number, b: number, c: string, d: any, e: number[], f: any[] ) => { console.log('something); } 

Such constructions can be avoided by including parameters in the object and transferring functions to a single object. Here interfaces will help us. This mechanism is in TypeScript:

 interface MyParameters { a: number, b: number, c: string, d: any, e: number[], f: any[] ... ... } let myFunction = (myParameters: MyParameters) { } 

Classes


It is necessary to develop the habit of grouping related variables (properties) and functions (methods) into a single construct, which in programming is called a class. To try this out in practice, create the file myPoints.ts and put the following code into it:

 class MyPoint {  x: number;  y: string;  draw() {    //   ,    x    this    console.log("X is: " + this.x);    console.log("X is: " + this.y);  }  getDistanceBtw(another: AnotherPoint) {   //     } } 

Access to class properties and methods


We grouped related variables and methods into a single class. Now we need to figure out how to work with them. To do this, create an instance of the class:

 let myPoint = new MyPoint() //MyPoint -    myPoint.x = 2;              //  x myPoint.y = "a";            //  y myPoint.draw();             //  draw 

The file myPoints.ts can be myPoints.ts and run what happened:

 tsc myPoint.ts | node myPoint.js 

Note that before assigning the properties of a value class, you need to create an instance of it. Is there a way to set the property values ​​during class creation? Such a method exists and exists thanks to the designers.

Constructors


A constructor is a method that is automatically called when creating instances of a class. The constructor allows you to set property values. Here is an example of working with an instance of a class in which the capabilities of constructors are not applied:

 let myPoint = new MyPoint() myPoint.x = 2; myPoint.y = "a"; 

The same, using the constructor, can be rewritten as:

 let myPoint = new MyPoint(2, "a"); 

However, in order for the above example to work, you need to make changes to the class by setting its constructor:

 class MyPoint {  x: number;  y: string;  constructor (x: number, y: string) {    this.x = x;    this.y = y;  }  draw() {    //   ,    x    this    console.log("X is: " + this.x);    console.log("X is: " + this.y);  }  getDistanceBtw(another: AnotherPoint) {   //     } } 

Optional parameters in the constructor


What if we decided to use a constructor, but we want the explicit setting of parameters when creating class instances to be optional? This is possible. To do this, use the question mark ( ? ) In the constructor. This sign allows you to define parameters that, when creating an instance of a class, are optional:

 class MyPoint {  x: number;  y: string;  constructor (x?: number, y?: string) { //   "?"  ":"    this.x = x;    this.y = y;  }  draw() {    //   ,    x    this    console.log("X is: " + this.x);    console.log("X is: " + this.y);  }  getDistanceBtw(another: AnotherPoint) {   //     } } //       myPointA  MyPoint let myPointA = new MyPoint() myPoint.x = 2; myPoint.y = "a"; myPoint.draw(); //       myPointB  MyPoint let myPointB = new MyPoint(2, "b"); myPointB.draw(); //       myPoint  MyPoint let myPointC = new MyPoint(2); //   ,   Y     myPointC.draw(); 

Access modifiers


An access modifier is a keyword that is used with a property or member of a class to control access to it from outside. In TypeScript, there are three access modifiers: public , protected and private . By default, all class members are public - this is similar to using the public access modifier with them, that is, they can be read and modified externally. Using the access modifier private allows you to prevent external mechanisms from working with class members. For example, here we used this modifier with x and y properties:

 class MyPoint { ... private x: number; private y: string; //       public draw() {  // - } ... } let myPoint = new MyPoint(); myPoint.x = 3; 

Attempting to use the myPoint.x construct when working with an instance of a class will result in an error, because the property is declared with the access modifier private .

Auxiliary equipment of designers


Above, we added a constructor to our class as follows:

 private x: number; public  y: string; constructor (x: number, y: string) {    this.x = x;    this.y = y; } 

TypeScript allows you to write the same thing in abbreviated form:

 constructor (private x: number, public y: string) {} 

Everything else will be done automatically (I bet you will often see this in Angular applications). That is, we do not need the following code:

 private x: number; public  y: string;  this.x = x; this.y = y; 

Getters and Setters


Suppose now that the MyPoint class looks like this:

 class MyPoint {  constructor (private x?: number, private y?: string) {}  draw() {    // -  }  drawAnotherThing() {   //  -  } } 

We absolutely know that we cannot work with the x and y properties outside the instance of the MyPoint class, since they are declared using the access modifier private . If you need to somehow influence them or read their values ​​from the outside, we will need to use getters (for reading properties) and setters (for their modification). Here's what it looks like:

 class MyPoint {  constructor (private x?: number, private y?: string) {}  getX() { // X    return this.x;  }  setX(value) { //  X       this.x = value;  } } //   x  ,     myPoint //   setX()    X let myPoint = new MyPoint(); myPoint.setX = 4; console.log( myPoint.getX() ); //  4; 

The mechanism of setters and getters allows you to set restrictions applied when setting or reading class properties.

Auxiliary mechanisms for working with setters and getters


Instead of using a construct like myPoint.setX() to set the value of x , what if you could do something like this:

 myPoint.X = 4; //  X ,    ,       

In order for such a mechanism to work, when declaring getters and setters, you need to put the get and set keywords in front of the function name, that is, comparing it with the previous examples, separate these words with a space from the function name following them:

 class MyPoint {  constructor (private x?: number, private y?: string) {}  get X() { //     X    return this.x;  }  set X(value) { //     Y    this.x = value;  } } 

In addition, the common practice is to use underscores at the beginning of property names ( _ ):

 class MyPoint {  constructor (private _x?: number, private _y?: string) {}  get x() { //     X    return this._x;  }  set x(value) { //     Y    this._x = value;  } } 

Modules


When you start creating real-world applications, you will find that more than one class is needed in them. Therefore, it would be good to find a tool that allows you to create classes so that they can be used in other files and in the classes declared in these files, that is, we need tools to write modular code. Such tools are already available in TypeScript. In order to consider them, we will bring the code in the myPoint.ts file to the myPoint.ts form:

 export class MyPoint { //      export  constructor (private _x?: number, private _y?: string) {}  get x() {    return this._x;  }  set x(value) { //     x    this._x = value;  }  draw() {    // -  } } 

Thanks to the export keyword, the class described in the MyPoint.ts file can be made visible in other files by importing it into them using the import keyword.

In order, for example, to use the MyPoint class in the MyPoint file, it must be imported:

 import { MyPoint } from './myPoint'; class Main {  let MyPoint = new MyPoint(4, "go to go");  MyPoint.draw();  } 

Please note that the main.ts and myPoint.ts are in the same directory.
image

Results


In this article, we looked at the basics of TypeScript, which are needed in order to start writing applications on Angular. Now you can understand the device of the Angular-code, which means that you, among other things, will be able to effectively master the manuals that are devoted to this framework and imply knowledge of TS.

Dear readers! If you are well versed in Angular - please tell beginners about how you studied it, and advise good educational materials on it.

Source: https://habr.com/ru/post/344502/


All Articles