TypeScript Foundation Point Collation

Posted by harlequeen on Wed, 15 May 2019 20:44:07 +0200

1. Features of TypeScript

1. Support ES6 specification

2. Strong IDE support (Integrated Development Environment)

  1. Allows you to specify types for variables, reducing the chance that you will make mistakes during development.

  2. Syntax hints, when IDE writes code, it will prompt you for the classes, variables, methods, and keywords you can use based on your context.

  3. Refactoring, easy to modify variables, methods, file names, when you modify the IDE will help you use these variables, methods to modify the place.

3. The development language of Angular2.

2. Setting up a development environment for TypeScipt

1. We need compiler s.

We need to compile the TypeScript file at the end of.ts to the JavsScript file at the end of.js because some browsers do not support ES6 syntax and cannot run the program directly, so we need to compile it to JavaScript syntax that supports ES5.

2. Develop using online compiler TypeScript

3. Build a local development environment

  1. NPM insatll typescript-g global installation

  2. tsc --version View Version

  3. ./demo/hello.ts

  4. TSC. /demo/hello.ts generates a hello.js file in its sibling directory

  5. It's a little cumbersome every time, so let's start using IDE, which can help me do these things

    Create project directory Open CMDtsc --init generates tsconfig.json configuration file

    {
      "compilerOptions": {
        "target": "es5",//Translated Grammar
        "module": "commonjs",//Using the commonjs module
        "outDir": "./js/",//Translated files are stored in the. /js folder
        "rootDir": "./tscript/",//Put the files you need to translate in the. /tscript folder
        "esModuleInterop": true
        // The esModuleInterop depends on the content module set.
        // If you have "module": "commonjs", you only need to enable "esModuleInterop": true.
        // If you have "module": "es2015" or "module": "esnext",
        //You must also enable "allowSyntheticDefaultImports": true to import CommonJS modules (such as React) as defaults.
      }
    }

    We use the above configuration;

    Let's use Visual Studio Code today to demonstrate that it's easier to open a created project folder with a hint plug-in on webstorm.

    Create new tscript and js folders to store typescript and javascript files, respectively. Create a new test.ts file in the tscript directory.

    Open > Menu > Terminal > Run Task >

    After clicking Run, as long as we modify the code of ts file and save it, it will be translated automatically

    Now that's configured, you can develop normally.

3. Learning Strings

1. Multi-line string

In JS we declare that variables are not newline

var str = 'aaa
bbb
ccc'
/*It would be wrong to write in the above way. We usually use the following way*/
var str = 'aaa'+
'bbb'+
'ccc';

Writing of multi-line strings in TS wrapped in ``

var str = `aaa
bbb
ccc`
//You can wrap any line in this
//Translation to JS is like this
var str = 'aaa\nbbb\nccc'

2. String Template

var myName = 'huoqingchi'
var getName = function () {
    return 'huoqingchi';
}
console.log(`hell ${myName}`);//Expressions can be written directly
console.log(`hell ${getName()}`);//Method can also be called directly
//Remember that the reason you can do this is because they are written in ``.

Next, let's see the power of string templates, splicing a piece of HTML with strings

var myName = 'huoqingchi';
console.log(`<div>
    <h1>Hello, I am ${myName}</h1>
    <h1>${getName()}</h1>
</div>`);//Readability and writing are great.

3. Automatically splitting strings

When you call a method with a string template, the value of the expression inside the string template is automatically assigned to the parameter in the called method.

function test(template,name,age) {
    console.log(template)
    console.log(name)
    console.log(age)
};
var myName = 'huoqingchi';
var getAge = function(){
    return 18;
}
//If you want to use the string splitting feature instead of calling the test method directly in parentheses, you need to use ``.
//The first parameter is your string template.
//The second parameter is the value of the first expression you see.
//The third parameter is the value of the second expression you see.
test`hello ${myName},${getAge()}`

Output results:

4. New characteristics of parameters

1. Parameter Types

We can use a colon to specify the type of parameter after its name

Because I've specified a string type for str, I get an error when I assign it a numeric type. This only happens when we write a.ts file and when it translates it into a.js file for us.

But why did I make a mistake when I explicitly did not specify a type for the code above?

This is because TypeScript has a type inference wit, and if you store string values for this variable at a time, it will stipulate that you can only store string values for this variable.

If you want a variable to be both string and numeric;

We can assign an anytype to this variable, which means it can store any type of value.

In addition to string and any types, we have
1, number //value
​ 2,boolean //true||false
3. The void //void used to declare the return value of a method means that this function does not need a return value, and you can also set the return class for this method.In addition to setting classes for methods, we can also set types for methods'parameters, specifying the parameters that must be passed in.

4. Custom type:

class Person {
    name:string;
    age:number;
}
var zhangsan :Person = new Person();
zhangsan.name = 'zhangsan'
zhangsan.age = 18;
//When you declare the Person type, calling it will grammatically prompt you what attributes it currently has and what their class nature is.

If you declare a variable, declaring a function with the same name will result in an error.

2. Default parameters

At this point we can set a default value for the third parameter:

Keep in mind that the parameters you need to set default parameters are ordered from the bottom, as the incoming parameters are matched from the first

3. Optional parameters

Use? After method parameter declaration to indicate that this parameter is optional

Running at this time will output:

There are two things to note when using optional parameters:
1. What to do when the optional parameter is not passed in and the b parameter is not passed in, but if I call it directly in the function body, I will get an error.
Example: console.log(b.lenght)//This error is very common undefined cannot be dotted

2. Optional parameters cannot be declared before required parameters;

5. New Features of Functions

1. Rest and Spread operators

1.1 Declares methods that can pass in any parameter (primary)

function func1(...args) {//This... is the Rest and Spread operator
    //args parameters declared with...can pass in any number of parameters
    args.forEach(function (arg) {
        console.log(arg)
    })//args is an array that uses arguments internally to observe the translated.js file.
};
func1(1,2,3);
func1(4,5,6,7,8);

Output results:

1.2 Calls to a fixed number of methods on an array of any length

function func1(a,b,c) {
    console.log(a);//The first pass in was 1,2 without a third parameter so c is undefined
    console.log(b);//The second time we passed in 5,4,2,34,2 but we only accepted the three parameters a,b and c, so we only took the first three.
    console.log(c);
};
var args = [1,2];
func1(...args);//This gives each item in the args array and passes it as an argument.
var args2 = [5,4,2,34,2];
func1(...args2);//This syntax is not supported by TypeScript, so errors will occur, but the compiled js file will work correctly.

Run the compiled js file to output the results:

2. Geneor function

It controls the execution of functions and manually suspends and restores code execution.

function* get() {//Adding * between function and function name is the generator function
    console.log("start");
    yield;//yield will stop the function interrupt from executing further
    console.log("finish")
}
var func1 = get();//If it is not useful to call the get function directly, you need to assign it to a variable.
func1.next();//A call to.next() allows the function to execute.//output start;
func1.next();//Output finish, //each call to next causes the function to execute and stay at the next yield.

Because this grammar TypeScript is not yet supported, it is part of the es6 specification, so we used it babel translation.

function *get() {
    while (true) {//This loop is not always executed, only if price>limit below is true
        yield Math.random()*100;
    }
}
var priceG = get();//Get get execute
var limit = 15;//Minimum 15
var price = 100;//Start 100
while (price>limit) {//Stop if it is less than 15.
    price = priceG.next().value;//The random number returned by yield in the get function is obtained from.value and assigned to price
    console.log(`${price}`)//Output yield returned value
}
console.log(`${price}`);//If you get a number less than 15, it will pop up

Output results:

3. Destructive Expression

An expression splits an object or array into any number of variables.

3.1 Object

function get() {
    return {
        xing:'huo',
        age:18
    }
}
var {xing,age} = get();
//The variable name in {} should be the same as the property name in the object your function returns
//If you want to change your name: {xingshi:xing,age}
//console.log(xingshi);//'huo'
console.log(xing);//'huo'
console.log(age);//18
function get() {
    return {
        xing:'huo',
        yifu:{//If you return another object
            kuzi:400,
            shangyi:200
        }
    }
}
          //So we can destruct the properties inside
var {xing,yifu:{kuzi}} = get();
console.log(xing);//'huo'
console.log(kuzi);//400

3.2 Array

var arr1 = [1,2,3,4];
var [number1,number2] = arr1;
console.log(number1)//1
console.log(number2)//2
//If you want to take 3 and 4
var [, , number1, number2] = arr1;
//Stand, but I won't take it out.
console.log(number1)//3
console.log(number2)//4
//If you want to take 1 and 4
var [number1, , number2] = arr1;
console.log(number1)//1
console.log(number2)//4

3.2 Destruction expression shared with Rest operator

var arr1 = [1,2,3,4];
var [number1,number2,...shengyu] = arr1;
console.log(number1)//1
console.log(number2)//2
console.log(shengyu)//[3,4]
var arr1 = [1,2,3,4];
function test([number1, number2, ...shengyu]) {
    console.log(number1)//1
    console.log(number2)//2
    console.log(shengyu)//[3,4]
}
test(arr1);//Parameters of type'number[]'cannot be assigned to parameters of type'[any, any,... Any[]', but do not affect our use.

6. Expression and Cycle

1. Arrow expression

Used to declare anonymous functions, eliminating this pointing problems with traditional anonymous functions.

Var sum = (arg1, arg2) => arg1+arg2; this is the simplest line of arrow expressions.If the return value has only one line, you can omit {} and you do not need to write the return method.You need to write {} if you have more than one line.

Var sum = () => {} is written this way if there are no parameters.

Var sum = Arg => {return arg} Parentheses can be omitted if there is only one parameter.

Example:

var myArray = [1,2,3,4,5,6];
console.log(myArray.filter(value => value%2 == 0))
//filter() means careless, () contains an expression and returns if the remaining 2==0, resulting in [2,4,6].

The best benefit of an arrow expression is that this points to:

function get(name:string) {
    this.name = name;
    // setInterval(function () {
    //     console.log("name is"+this.name);
    //     //Nothing because this points to window
    // }, 1000);
    setInterval(() => {
        console.log("name is " + this.name);
        //Same as you might think, because this is the context in which it is located
    }, 1000);
}
var stock = new get("huo");

2. Cycle

1,forEach

2,for...in...

3,for...of...

7. Object-Oriented Features

1. Class

Classes are the core of TypeScript, and when you develop with TypeScript, most of your code is written in them.

The definition of a class, its constructors, and its inheritance are described here.

class People {//Methods for declaring classes in TypeScript
     name;//attribute
     getName(){//Method
        console.log("huoqingchi");
    }
    //Class has properties and methods
}
var p1 = new People();//We instantiated this class with new and assigned it to p1
p1.name = "rope";
p1.getName();
//We can have multiple instances of a new class with the same properties and methods, but in different states.
var p2 = new People();//We can instantiate a class and assign it to p2
p2.name = "scarf";
p2.getName();

Access Controller

There are three properties and methods of a management class that can be called with declarative effects.

1,public
class People {
     public name;
     public getName(){
        console.log("huoqingchi");
    }
    //The properties and methods of public can be accessed inside the class | outside the class. It is also the default and can be written without writing.
}
2,private

3,protected

Constructor of class

class People {
    constructor(){//It is the constructor of a class, a special method.
        //This method will be executed when this class is instantiated.
        console.log("hhh")
    } 
}
var p1 = new People();//hhh

Usefulness: When instantiating a person, you must assign him a name, etc.

//First Writing Method
class People {
    name;//A name attribute is declared
    constructor(name:string){//Accept the value from instantiation and set the parameter type here
        this.name = name;//This will access the name property declared above and pass it the value we received
    };
    getName(){
        console.log(this.name);
    } 
}
var p1 = new People("rope");//Pass in a value to the constructor when instantiating here
p1.getName();//rope
//Second Writing
class People {
    constructor(public name:string){//Accept the value from instantiation and set the parameter type here
        //This is written by the People class to create a name attribute and assign the value passed in to it.
        //Explicit declaration of access controllers is required on constructors
    };
    getName(){
        //If the name in the constructor does not declare an access controller, there is no name attribute in the People class.
        console.log(this.name);//So it's not available here.
    } 
}
var p1 = new People("rope");//Pass in a value to the constructor when instantiating here
p1.getName();//rope

Class Inheritance

1,extends

Inheritance is possible through the extends keyword

At this time, the properties and methods of People are also available on the p1 that Student instantiates.

There are no instances of the property and method People in the Student class.

2,super

First usage: call the parent class's constructor

class People {
    constructor(public name:string){
        //This is called by the following super.
        //This is written by the People class to create a name attribute and assign the value passed in to it.
        console.log("People")
    };
    getName(){
        console.log(this.name);
    } 
}
class Student extends People {
    constructor(name: string, public code:string){//Instantiate a student must have a name and a number
         //This notation is created by the Student class as a code attribute and assigned to it the value passed in.
        super(name);//The super passes the name by calling the constructor of the parent class (People).
        console.log("Student")
    }
    getCode(){
        console.log(this.code);
        console.log(this.name)
    }
}
var p1 = new Student("huo","18")
p1.getCode()

Output results, note the order:

Sup calls People's constructor Student executes p1.getCode() and outputs code and name in sequence.

Second usage: other methods of the parent class can be called

class People {
    mifan(){
        console.log("Eat rice");
    } 
}
class Student extends People {
    chifan(){
        super.mifan();//Other methods of the parent class can be invoked directly through super-dotting.
        this.xuexi();
    }
    private xuexi() {
        //This method itself can be called outside of Student and I want him to have to eat before learning.
        //That is, only let him be called inside the Student, so set the access controller for him.
        console.log("Learn after eating rice");
    }
}
var p1 = new Student();
p1.chifan();

Output results:

2. Generics

The type of parameterization that generally limits the contents of a collection.

class People {
    constructor(public name:string){
    };
}
class Student extends People {
    constructor(name: string, public code:string){
        super(name);
    }
}
class Teacher extends People {
    constructor(name: string, public code: string) {
        super(name);
    }
}
var arr: Array<People> = [];//<>means that my arr ays can only store data of the same type as People
arr[0] = new Student("huo", "18");
arr[1] = new Teacher("huoqingchi", "23");
console.log(arr)

Output results:

There are warnings if you store other types of data:

3. Interface

Used to establish a code convention that other developers must follow when calling a method or creating a new class.

Usage in the first section: declaration of parameter type as a method

//Declare an interface using interface
interface jiekou {//The name of the interface is given to jiekou
    name:string;
    age:number;
}
class People{
    constructor(public consig: jiekou){//Declarations that make an interface a parameter type of a method

    }
}
var p1 = new People({
    //When you call this method, TypeScript checks to see if the parameters you passed in conform to the format agreed upon by the interface.
    name:"huoqingchi",
    age:18
    //There can be no more or fewer parameters, and null can be filled in if there are no values.
})

Second usage: declare a method with an interface.

interface People {
    chi();//The People interface has a way to eat.
}
class Student implements People {
    //Implements means that the Student class implements the People interface
    //That is, it must implement the methods within this interface.
    chi(){
        console.log("I am vegetarian");
    }
}
class Teacter implements People {
    chi(){
        console.log("I eat meat");
    }
}

4. Modules

Modules help developers split code into reusable units.Developers can decide for themselves to expose those resources (classes, methods, variables) in a module for external use. Those resources can only be used within a module, and a file is a module.

./demo/ide/tscript/test.ts

export var a = 10;//export means exposure.
var b = 20;//Not exposed can only be used in this module.
export function fn1() {
    console.log("I am fn1")
}
function fn2() {
    console.log("I am fn2")
}
export class CLazz1 {
    constructor() {
        console.log("I am CLazz1 class")
    }
}
class CLazz2 {
    constructor() {
        console.log("I am CLazz2 class")
    }
}

./demo/ide/tscript/test2.ts

import { a, fn1, CLazz1} from './test';
//Import means import, where from is imported, and {} imports those things.
console.log(a);
console.log(fn1);
console.log(CLazz1);
//A module can be import ed or export ed
export function fn3() {
    console.log("I am fn3")
}

Output results:

5. Notes

Annotations are elements (classes, methods, variables) of a program plus more intuitive descriptions that are not related to the business logic of the program but are used by specified tools or frameworks.

import {Component} from '@angular/core';//angular is used here, and vue,react will be added later.
@Component({//Here are the notes
    selector:'app-root',
    templaterUrl: './app.component.html',//Load into app.component.html page
    styleUrls:['./app.component.css']//Load app.component.css style file
})
export class AppComponent {//When you load this class with angular it will execute the above comment
    title = "app works!";
}

app.component.html

<h1>{{title}}</h1><!--The page will display app works!-->

6. Type Definition Files (*.d.ts)

Type definition files are used to help developers use existing JavaScript toolkits in TypeScript, such as JQuery;

We used typings,npm install -g typings.

. /demo/ide is under the project folder.

Open the CMD window and run typings install dt~jquery --global//Here's an example of jquery, if you need another memory change.

Where "dt~" is the meaning of a definition using the DefinitelyTyped type, which is recognized by vscode.

Before installation:

After installation: The typings folder is automatically generated

Concluding remarks

We're done with the basics of TypeScript, and we'll sort out the updates based on feedback.
Documentation for TypeScript: http://www.typescriptlang.org/docs/home.html
My blog: https://www.cnblogs.com/rope/
My github: https://github.com/mufengsm
My mailbox: scarf666@163.com

Author: Rope

Topics: Javascript TypeScript Attribute REST