Introduction of TypeScript

define

As we all know, JavaScript is not an object-oriented language, but an interpreted functional programming language. When the front-end Web is not very complex, JavaScript can handle a variety of needs, but as the front-end pages become more complex, JavaScript becomes less capable, and TypeScript is designed to address this situation. TypeScript is an object-oriented language that supports many object-oriented features at the same time, making it possible to create more robust and easily extensible programs. Also, TypeScript extends JavaScript’s syntax so that any existing JavaScript program can work in TypeScript unchanged.

According to Wikipedia: TypeScript is a free and open source programming language developed by Microsoft that is a strict superset of JavaScript with optional static typing and class-based object-oriented programming.

The advantage of the TypeScript

As you can see, more and more front-end frameworks are using TypeScript. What are the benefits of TypeScript? Here are some common advantages:

  • More rules and type restrictions make code more predictable, more controllable, and easier to maintain and debug.
  • Support for modules, namespaces, and object orientation makes it easier to organize code to develop large, complex programs.
  • TypeScript compilation steps catch errors before they are run.
  • Angular2+ and Ionic2+ use TypeScript by default, while some popular front-end frameworks such as vue.js and React.js are starting to support TypeScript.
  • .

Environment set up

As the saying goes, “To do a good job, you must first sharpen your tools.” Learning a new language and technology must first understand its development environment.

Install the TypeScript

TypeScript provides two main ways to access TypeScript tools:

  • Via NPM (Node.js package manager)
  • Install the TypeScript plug-in for Visual Studio

The latest versions of Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. If your Visual Studio doesn’t already support TypeScript, You can use the Visual Studio download page link to obtain the install plug-in. In the meantime, for NPM users, you can use the following command to install TypeScript tools.

npm install -g typescript
Copy the code

Besides the above two ways, we can also use the TypeScript provide online environment to experience the glamour of the TypeScript: www.typescriptlang.org/play/index….

Create TypeScript files

Open the editor and type the following code into the greeter.ts file.

function greeter(person) {
    return "Hello, " + person;
}

let user = "jack ma";

document.body.innerHTML = greeter(user);
Copy the code

Compile the code

TypeScript uses.ts as an extension, but this code is just JavaScript, and to run it, you need to compile it. On the command line, run the TypeScript compiler:

tsc greeter.ts
Copy the code

The output is a greeter.js file that contains the same JavsScript code as in the input file. At this point, we are ready to run the code.

Type annotations

Type annotations in TypeScript are a lightweight way to add constraints to functions or variables. In this example, we want the greeter function to take a string argument. We can do this:

function greeter(person: string) {
    return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.innerHTML = greeter(user);
Copy the code

Recompile and you will see an error:

Greeter. ts(7,26): error TS2345: Argument oftype 'number[]' is not assignable to parameter of type 'string'.
Copy the code

interface

Let’s develop an example using an interface that describes an object with firstName and lastName fields. In TypeScript, two types are compatible if their internal structure is compatible. This allows us to implement an interface that only needs the necessary structural shape, without having to have an explicit implements clause.

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstName + "" + person.lastName;
}

let user = { firstName: "Jane", lastName: "User" };

document.body.innerHTML = greeter(user);
Copy the code

class

TypeScript supports new features of JavaScript, such as class-based object-oriented programming. Let’s create a Student class with a constructor and some public fields.

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + "" + middleInitial + "" + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + "" + person.lastName;
}

let user = new Student("Jane"."M."."User");

document.body.innerHTML = greeter(user);
Copy the code

Rerun TSC Greeter.ts and you should see the generated JavaScript code as before. TypeScript classes are simply shorthand for prototyping object-oriented programming commonly used in JavaScript.

Grammatical features

TypeScript introduces a number of syntactic changes compared to JavaScript, some of the most important ones are listed below.

Character string

Multiline string

Use ‘ ‘to wrap a cross-line string, as in:

var html = `<div>
<span></span>
</div>`
Copy the code

String template

Templates can be used in multi-line strings, as shown in the following example:

var names = 'daocheng';
function getImg() {
  return '<i></i>'
}

var html = `<div>${names}
<span>${getImg()}</span>
<div>
`
Copy the code

### Automatically split strings

function getData(template, name, age) {
    console.log(template);
    console.log(name);
    console.log(age);
}

var names = 'daocheng'; var age = 23; GetData 'Hello, my name is${names}This year, I${age}At the age of `Copy the code

parameter

The parameter types

The types of the parameters in the Typescript are Boolean/number/string array/tuple enum/any/(null, and undefined)/void/never. Tuple, enumerations, arbitrary values, void types, and never are unique to Javascript.

Type declaration and default parameters

To declare variables in Typescritpt, add type declarations such as Boolean or String. By performing type checking at compile time with static type constraints, you can avoid some low-level errors of type mixing. Example:

var names = 'daocheng';
function getData(name: stirng, age: number): boolean {
    return true
}
Copy the code

Typescript also supports initialization of default parameters. If a parameter of a function is set to a default value, this parameter is set to the default value when the function is called, if no value is passed to this parameter or if undefined is passed. Example:

function max(x: number, y: number = 4): number {
    return x > y ? x : y;
}
letresult1 = max(2); / / normalletresult2 = max(2, undefined); / / normalletresult3 = max(2, 4, 7); / / an errorletresult4 = max(2, 7); / / normalCopy the code

Optional parameters

In javascript, every function of the function being called is optional. In typescript, every argument to every function being called is mandatory. At compile time, the function is checked to see if each argument is passed a value. In short, the number of arguments passed to a function must match the number of arguments defined by the function. Such as:

function max(x: number, y: number) {
    if(y){
        return x > y ? x : y;
    } else {
        return x
    }
}
let result1 = max(2);
letresult2 = max(2, 4, 7); / / an errorletresult3 = max(2, 4); // Note: Optional parameters must be placed after the default parametersCopy the code

function

The residual function

The rest of Typescript’s arguments are used when you need to manipulate multiple arguments at once or when you don’t know how many arguments will be passed in. Example:

functionsum(x: number, ... restOfNumber: number[]){let result = x;
    restOfNumber.forEach(value => result += value);
    return result;
}
let result1 = sum(1, 2, 3, 4, 5, 6);
console.log(result1);

let result2 = sum(2);
console.log(result2);

let result3 = sum(2, 5);
console.log(result3);
Copy the code

The generator function

Control function execution process, can manually interfere with the function execution. Example:

function getPrice(stock) {
    while (1) {
        yield Math.random() * 100;
    }
}
var priceGenerator = getPrice('dcc');
var limitPrice = 51;
var price = 100;
while (price > limitPrice) {
    price = priceGenerator.next().value;
    console.log(`this generator return ${price}`);
}
console.log(`buying at ${price}`);
Copy the code

Destructor expression

Destructor expressions, also known as deconstruction, are an important feature of ES6. In version 1.5, Typescript added support for structures, which correspond a declared set of variables to the values of an array or object of the same structure. Fractional group deconstruction ([]) and object deconstruction ({}).

An array of deconstruction

let imput = [1, 2];
let[first, second] = input; console.log(first); // equivalent to inputp[0] console.log(second); // input[1]functionF ([first, second]) {console.log(first + second)} f{[1, 3]} // Result is 4let[first, ...rest] = [1, 2, 3, 4]; console.log(first); //1 console.log(second); / / / 2 and 4Copy the code

Object to deconstruct

let test = {
    x: 0,
    y: 0,
    width: 15,
    heights: {
        height1: 10,
        height2: 20
    }
};
let { x, y: myY, width, heights: {height2} } = test; console.log(x, myY, width, height2); // output: 0,10,15,20Copy the code

Arrow expression

Used to declare anonymous functions, eliminating the this pointer problem of traditional anonymous functions. Such as:

function Test1(names: string) {
    this.names = names;
    setInterval(function() {
        console.log('my name is '+ this.names); }}, 1000)function Test2(names: string) {
    this.names = names;
    setInterval(() => {
        console.log('my names is ' + this.names)
    }, 1000)
}

var a = new Test1('daocheng'); //undefined
var b = new Test2('daocheng'); //daocheng
Copy the code

cycle

There are three advanced loops involved in typescritpt: forEach(), for in, and for of.

forEach

var myArray = [1, 2, 3, 4];
myArray.name = 'daocheng'; myArray.forEach(value => console.log(value)); // result is 1,2,3,4 // features: not supportedbreak, will ignore (name)Copy the code

for in

var myArray = [1, 2, 3, 4];
myArray.name = 'daocheng';

for (var n inMyArray) {console.log(n)} // the result is 1,2,3,4 // characteristic: the result of the loop is the key value of the object or array. canbreak
Copy the code

for of

var myArray = [1, 2, 3, 4];
myArray.name = 'daocheng';

for(var n of myArray) {console.log(n)} {console.log(n)} When the loop is a string, each character in the string is typed outCopy the code

class

Traditional JavaScript programs use functions and prototype-based inheritance to create reusable “classes.” This is not very friendly for developers accustomed to object-oriented programming, which is supported in Typescript.

Declaration of a class

class Car {
    engine: string,
    constructor(engine: string) { 
        this.engine = engine;
    }
    drive(distanceInMeters: number = 0) { 
        console.log(`aaa is running` + this.engine)
    }
}

let car = new Car('petrol');
car.drive(100)
Copy the code

Class encapsulation, inheritance, polymorphism

Encapsulation, inheritance and polymorphism are three characteristics of object – oriented. The above example writes the behavior of the car into a class called encapsulation. In Typescript, the extends keyword is easy to implement. Such as:

inheritance

Inheritance is a special and general relationship between classes, which can be understood as “is A” relationship. In inheritance relationships, subclasses can unconditionally inherit the methods and attributes of their parent class.

class Car {
    engine: string;
    constructor(engine: string) {
        this.engine = engine;
    }
    drive(distanceInMeter: number = 0){
        console.log(`A car runs ${distanceInMeter}m
        powered by` + this.engine)
    }
}

class MotoCar extends Car {
    constructor(engine: string) {
        super(engine)
    }
}

let tesla = new MotoCar('electricity'); tesla.drive(); // The tesla instance of subclass MotoCar calls the drive() method of its parent class Car.Copy the code

polymorphism

Polymorphism is a kind of polymorphism processing mechanism that can be realized by executing logic by judging the parameters passed.

class Car {
    engine: string;
    constructor(engine: string) {
        this.engine = engine;
    }
    drive(distanceInMeter: number = 0){
        console.log(`A car runs ${distanceInMeter}m
        powered by` + this.engine)
    }
}

class Jeep extends Car {
    constructor(engine: string) {
        super(engine)
    }
    drive(distanceInMeters: number = 100) {
        console.log('jeep... ')
        returnsuper.drive(distanceInMeters); }}let landRover: Car = new Jeep('petrol'); // Implement polymorphismCopy the code

The drive() method in the Jeep subclass overrides the Drive () method in Car, so that the drive() method behaves differently in different classes. Note: Super () must be called in the constructors of subclasses and derived classes, which implements the superclass constructor.

Parameter properties

Parameter properties are declared by adding an access qualifier to the constructor’s parameters. Parameter attributes make it easy to define and initialize class members in one place.

class Car {
    constructor(public engine: string) {}
    drive() {}}Copy the code

An abstract class

Typescript has the concept of abstract classes, which are base classes inherited by other classes and cannot be instantiated directly. Unlike interfaces, abstract classes must contain some abstract methods and can also contain non-abstract members. Abstract methods in abstract classes must be implemented in derived classes.

abstract class Person {
    abstract speak(): void;
    walking(): void {
        console.log('walking');
    }
}

class Male extends Person {
    speak(): void {
        console.log('man wakling')}}Copy the code

interface

Interface plays an extremely important role in object-oriented design. It can be seen in 23 design patterns of Gof. Interface patterns have long been the Achilles heel of weakly typed languages like Javascript, and Typescript interfaces are used in a similar way to Java. Typescript interfaces are property, function, indexable, and class types. Angular uses class-type interfaces. We use the interface keyword to define interfaces and the implements keyword to implement interfaces.

interfance Animal {
    name: string;
    setName();
}

class Dog implements Animal {
    name: string;
    setName() {
        console.log(this.name)
    }
    constructor() {}} // Interface pays more attention to functional design, abstract class pays more attention to the embodiment of structural contentCopy the code

The module

Modules were introduced in ES6 and are supported in TypeScript. Use the import and export keywords to establish a connection between the two modules.

A decorator is a special type of declaration that can be attached to a class declaration, method, property, or parameter. A decorator has the @ symbol followed by a function name, such as @expression. Expression must be a function, and the decorator declaration method will be executed when the function is executed. Decorators are used to decorate attached themes and add additional behavior. (Decorators belong to the ES7 specification)

The Typescript source code officially provides method decorators, class decorators, parameter decorators, and attribute decorators. Each type of decorator takes very different parameters. Here I demonstrate two types of decorators. Such as:

function Component(component) {
    console.log('selector: ' + component.selector);
    console.log('template: ' + component.template);
    console.log('component init');
    return (target: any) => {
        console.log('component call');
        returntarget; }}function Directive() {
    console.log('directive init');
    return (target: any) => {
        console.log('directive call');
        return target;
    }
}

@Component({
    selector: 'person',
    template: 'person.html'
})
@Directive()
export class Person {}

let p = new Person();
Copy the code

Anders hejlsberg, lead architect of C# and founder of Delphi and Turbo Pascal, is involved in TypeScript development. Typescript is a superset of ES6. Optional static typing (note that it is not strongly typed) and class-based object-oriented programming have been added. (If you’re familiar with ES6, you can focus only on the classes and decorators sections.)

The generic

Generics are parameterized types that are used to restrict the contents of collections. Such as:

class MinHeap<T> { list: T[] = []; Add (Element: T): void { } min(): T {return this.list.length ? this.list[0] : null
    }
}

let heap = new MinHeap<number>();
heap.add(3);
heap.add(5);
console.log(heap.min())
Copy the code