📜 ⬆️ ⬇️

TypeScript syntax basics



In 2012, C # developers from Microsoft created TypeScript , a superset of JavaScript. It is designed to develop large applications, from 100 thousand lines. Let's take a look at examples of TypeScript syntax, its main advantages and disadvantages, and also consider the way to interact with popular libraries.

To whom it will be useful : Web-developers and developers of client applications who are interested in the possibility of practical use of the TypeScript language.

There are various tools that allow you to write code compiled into JavaScript: CoffeeScript, Dart, Uberscript, and others. These include the TypeScript programming language, which allows to fix some of the flaws inherent in JavaScript.
')

JavaScript flaws



The main advantages of TypeScript



Types of variables that TypeScript supports


  1. Number
  2. String
  3. Boolean
  4. Array
  5. Enum
  6. Any
  7. Void

They are used to declare variables, functions, classes, Generic types, and other constructs.

Functions


Function parameters are divided into optional and default.


By analogy with C #, a question mark after a variable means that its value can be omitted.

Function declaration


 [csharp] function getCarName(manufacturerName: string, model?: string): string { if (model) { return manufacturerName + " " + model; } return manufacturerName; } [/csharp] 

Callback functions


We can also pass a function as a parameter.

 [csharp] function numberOperation(x: number, y: number, callback: (a: number, b: number) => number) { return callback(x, y); } function addCallBackNumbers(x: number, y: number): number { return x + y; } function multiplyNumbers(x: number, y: number): number { return x * y; } console.log(numberOperation(5, 5, addCallBackNumbers)); // 10 console.log(numberOperation(5, 5, multiplyNumbers)); // 25 [/csharp] 

Calling the function numberOperation , we pass two parameters and a function as a callback.

Combining and Overloading Functions


Despite strict typing, in TS there is an opportunity to use the same function with different types of transmitted values. For example, depending on the type of the transmitted value, one function concatenates our numbers, and the second adds.

 [csharp] // 2      function addOvverload(x: string, y: string): string; // 2  int   int  function addOvverload(x: number, y: number): number; function addOvverload(x, y): any { return x + y; } [/csharp] 

OOP. Classes


Class _ {
;
();
constructor(); }
 [csharp] class Car { var mazda = new Car(1, "Mazda", "6"); console.log(mazda.getCarInfo()); class Car { //    id: number; name: string; model: string; //  ,   constructor(carId: number, carModel: string, model: string) { this.id = carId; this.name = carModel; this.model = model; } //      getCarInfo(): string { return "Car model = " + this.name + " model= " + this.model; } } var mazda = new Car(1, "Mazda", "6"); console.log(mazda.getCarInfo()); [/csharp] 

OOP. Static properties and functions


The static keyword is used to define static functions and properties.

 [csharp] class Formula { static PI: number = 3.14; static Half = 0.5; //    static getircleSquare(radius: number): number { return this.PI * radius * radius; } //    static getTriangleSquare(length: number, height: number): number { return this.Half * length * height; } } // .   Formula    var circle = Formula.getircleSquare(16); var triangle = Formula.getTriangleSquare(4, 7); console.log("  = " + circle); console.log("  = " + triangle); [/csharp] 

OOP. Inheritance


One of the key elements of OOP is inheritance, which is implemented in TS using the extends . With the help of extends we can inherit from the base class and describe the classes heirs.

 [csharp] interface IAnimal { //   —      name: string; danger: number; getInfo(): void; } class Animal implements IAnimal { //     IAnimal name: string; danger: number; constructor(name: string, danger: number) { this.name = name; this.danger = danger; } getInfo(): void { console.log(" . : " + this.name + ", : " + this.danger); } } class Fox extends Animal { tailLength: number; constructor(name: string, danger: number, tailLength: number) { super(name, danger); this.tailLength = tailLength; //   super —    , //        , //      . } getInfo(): void { super.getInfo(); console.log(" .  : " + this.tailLength + " "); } } var goose: Animal = new Animal("", 1); goose.getInfo(); var fox: Animal = new Fox("", 10, 1); fox.getInfo(); [/csharp] 

OOP. Interfaces


To define a custom data type without implementation in TS (and not only), interfaces are used. To declare an interface, the Interface keyword is used.

 [csharp] module InterfaceModule { //   IAnimal         //        . interface IAnimal { name: string; danger: number; getInfo(): string; } class Animal implements IAnimal { name: string; danger: number; constructor(name: string, danger: number) { this.name = name; this.danger = danger; } getInfo(): string { return this.name + " " + this.danger; } } var seal: IAnimal = new Animal("", 1); console.log(seal.getInfo()); } [/csharp] 

OOP. Encapsulation


To hide external access to the state of an object and control access to this state, TS uses two modifiers: public and private .

Inside our class we can write methods that are inaccessible from the outside and manipulate with their help.

This is implemented as in C #:

 [csharp] module Encapsulation { class Animal { private _id: string; name: string; danger: number; constructor(name: string, danger: number) { //    _id     . this._id = this.generateGuid(); this.name = name; this.danger = danger; } private generateGuid(): string { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; } public getInfo(): string { return "Id = " + this._id + " name = " + this.name + " danger = " + this.danger; } } var parrot: Animal = new Animal("", 1); console.log(parrot.getInfo()); [/csharp] 

Thus, we have limited access to the generateGuid() method. By default, fields and methods have public access.

OOP. Generic


TypeScript allows you to create Generic types.

function _(_: ):
Where T is the type by which the function is typed. TS also supports typing interfaces and classes.

Class _
Interface _
Where T is the type by which the function is typed.

 [csharp] module GenericModule { function getId<T>(id: T) : T { return id; } // Generic  Animal,      generic    id class Animal<T> { private _id: T; constructor(id: T) { this._id = id; } getId(): T { return this._id; } } var cat = new Animal<number>(16); console.log("Cat id = " + cat.getId()); var dog = new Animal<string>("2327c575-2f7c-46c3-99f2-a267fac1db5d"); console.log("Dog id = " + dog.getId()); } [/csharp] 

Pass the type, set the Id to determine the type and return the information to our animal. Thus, Generic types are used.

Modules


One of the drawbacks of JavaScript is that a large number of files may overlap with each other, and there are peculiar conflicts. In TypeScript, this problem is solved by modules.

Modules are a namespace within which classes, enumerations, variables, functions, and other modules can be defined. Any set of classes, interfaces, functions can be combined into some bracket and called a specific module. And then with this module you can easily and simply interact.

The module keyword is used to define a module .

 [csharp] import test = MyTestModule.MyTestClass; module CarModule { //   CarModule     iCar. export interface ICar { //   export    ,         .     export,        CarModule. id: number; carModel: string; model: string; getCarInfo(): string; } export class Car implements ICar { //   Car,    ICar id: number; carModel: string; model: string; //     ,  IntelliSence   ,     model constructor(carId: number, carModel: string, model: string) { this.id = carId; this.carModel = carModel; this.model = model; } getCarInfo(): string { var t = new test().getInfo(); return "Car model = " + this.carModel + " model= " + this.model + " " + t; } } } let car = new CarModule.Car(16, "", "2107"); console.log(car.getCarInfo()); [/csharp] 

Changes in terminology: it is important that the nomenclature has changed since TypeScript 1.5. So that there was no disagreement with the terminology of ECMAScript 2015, the “internal modules” became known as “namespaces”, and the “external modules” are now simply “modules”. That is, module X {clearly with a more preferred namespace X {.

Header files


To bind with some global variables, you need to include header files - this is one of the drawbacks of TypeScript. To communicate with external JavaScript scripts files in TS, you must use declarative or header files with the * .d.ts extension.

The header files of the main libraries are already described, and it is quite simple and easy to work with them. To do this, go to the site and connect the necessary set of header files, for example, jQuery. Then the main global variables that are used in jQuery are declared, and later they will be used in the TS file.

 [csharp] /// <reference path="../lib/typings/jquery.d.ts" /> class Cars { private cars: Array<Car> = new Array<Car>(); load(): void { $.getJSON('http://localhost:53923/api/Car', (data) => { this.cars = data; alert(' '); }); } displayUsers(): void { var table = '<table class="table">'; for (var i = 0; i < this.cars.length; i++) { var tableRow = '<tr>' + '<td>' + this.cars[i].id + '</td>' + '<td>' + this.cars[i].name + '</td>' + '<td>' + this.cars[i].model + '</td>' + '</tr>'; table += tableRow; } table += '</table>'; $('#content').html(table); } } window.onload = () => { var cars: Cars = new Cars(); $("#loadBtn").click(() => { cars.load(); }); $("#displayBtn").click(() => { cars.displayUsers(); }); }; [/csharp] 

TypeScript Disadvantages




Advantages of TypeScript



Instruments



Conclusion


TypeScript is an excellent wrapper that can greatly increase the productivity of the development team, while maintaining compatibility with existing code. TypeScript is supported in VisualStudio 2015 and interacts with ECMAScript 6.0. While JavaScript does not have strong typing, TypeScript is an excellent alternative that does not require much time to learn.

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


All Articles