The Typescript learning

According to tpyescript?

  • The program is easier to understand
  • More efficient
    • Jump between different code blocks and definitions
    • Automatic code completion and rich interface tips
  • Fewer mistakes
  • Very inclusive, very compatiblejavascript

1.typescriptThe installation:

1. Installation:

/ / installation
sudo npm install -g typescript

/ / check
tsc -v  // Normally, the TS version will be displayed

Copy the code

2. Unloading and reloading:

/ / uninstall typescript
sudo npm uninstall -g typescript

// Find the TSC directory and delete it

where tsc # /usr/local/bin/tsc
cd /usr/local/bin
rm -rf tsc

// Install it again
sudo npm install -g typescript
Copy the code

2. Type:

1. Basic Type:

ECMAScript recently defines eight data types:

  • 7The original data type
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol
    • BigInt
// Boolean type
let isDone:boolean =true;

// Number type
let age:number =24;

// A string of characters
let PlayerName:string = iverson;

// undefined
let u:undefined =undefined;

// null
let n:null =null;

// The number type can be assigned undefined
let num:number = undefined;

Copy the code
  • undefinedandnullIt’s all typessubtypesThat is, they can be assigned to any type of variable

2.anyThe type andThe jointType:

Any: Can be assigned to any type

// Any type: can be assigned to any type

let notSure:any="Any type";

notSure=24;

notSure=true;

notSure.myname;

notSure.getName();



Copy the code

Combined type: A type or B type…

🌰 can be a number or a string

let NumorString:number | string =24;

NumorString="Kobe"
Copy the code

An array of 3.ArrayAnd a tupletuple:

  • Array:

    // Array of numbers
    let arrofNumber:number[] = [1.2.3.4.5];
    
    arrofNumber.push(520);
    Copy the code
  • Class array – IArguments:

    //IArguments
    function test(){
        console.log(arguments);
        console.log(arguments.length); // Has the length attribute
        console.log(arguments[0]);  // You can use []
    
        let igr:IArguments = arguments;
    }
    
    Copy the code
  • Tuple: A tuple is simply an array that typifies each item of an array.

    // tuple: an array that defines each item of the array type
    
    let tuple:[string.number] = ["Wade".3];   / / ✅
    
    tuple=["Wade".3."Miami Heat"];    / / ❎
    Copy the code

3. The Interface movement:

The main function of interface in TS can be understood as defining some parameters, specifying the parameters in the variable and the type of the parameters. When using the parameters, there must be these corresponding types of parameters. The error will be reported if there are few or many parameters and the parameter type is incorrect.

  • rightobjectThe shape is described
  • rightclassforabstract
  • Duck TypingDuck type (type conjecture) : if something can swim, eat, and walk like a duck 🦆, it is called a duck

Example code:

  • ?Represents an optional property
  • readonlysaidread-only, do notModify the
interface Person{
    name:string, age? :number     / /? Represents an optional property
   readonly id:number // Can only read, cannot modify rewrite; Readonly is also used for properties
}

let kirk:Person={
    name:"kirk".age:18.id:9527
}

let xiaogang:Person={
    name:"Xiao gang".id:9275
}

kirk.id=1111;  // ❎ Cannot be modified after readonly
Copy the code

4. Function types and type inference:

1. Function type:

  • Colon ":" afterIt’s all aboutType interpretation
  • +? Before colon:Said the optional
  • ts,
// Function type
function add(x:number,y:number,z? :number) :number{
    if(typeof z ==="number") {return x+y+z; 
    }else{
        returnx+y; }}let all=add(2.99.1);
console.log(all)

// Function expression
const add2:(x:number,y:number,z? :number) = >number = add;

Copy the code

Use interface to describe functions:

interface ISum {
	(x:number.y:number,z? :number) :number
}
let add2:ISum = add;
Copy the code

2. Type inference:

Although there is no constraint on the type of STR, TS will infer that STR is of type string, so it cannot be named as another type of value

// Type inference for ts

let str="Dazzling.";

str=123   // ❎ above ts has inferred that STR is a string and cannot be assigned to a number
Copy the code

5. The class class:

Class 1.class:

  • Class (class) : The one that defines everythingabstractThe characteristics of
  • Object (object) : instance of the class
  • object-orientedoopThree major features: encapsulation, inheritance, polymorphism
    • Encapsulation: will be onOperation details of dataHidden, exposing only external interfaces; An add-in can access this object without knowing the external interface.
    • Inheritance: A subclass inherits its parent class and has its own specific features as well as the parent class’s
    • Polymorphisms are related classes that have a different response to the same method by inheritance. For example, cats and dogs both inherit from animals, but each has developed his own way of eating.
// Create an animal class (class. Ts)
class Animal{
    name:string;
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `}}const snake=new Animal("lisin");
console.log(snake.run());   / / lisin is running ~!
Copy the code

2. Installts-nodeAnd to run the code:

// sudo NPM install -g ts-node run class. Ts file ts-node classCopy the code

3.class.tsThe code:

class Animal{
    name:string;
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `}}const snake=new Animal("lisin");
console.log(snake.run()); // lisin is running~!

/ / inheritance
class Dog extends Animal{
    bark(){
        return `The ${this.name}Is woof woof woof! `}}const ahuang=new Dog("Huang");
console.log(ahuang.bark()); // A huang is wang Wang wang ~!

//🌵 polymorphic: Ahuang has its own run method
console.log(ahuang.run()); // Is running~!


class Cat extends Animal{
    constructor(name){
        super(name);
        console.log(this.name);
        this.name=name;
    }
    run(){
        return ` a callThe ${this.name}The cat is running around with the ball of wool... `}}const maomao=new Cat("Maomao");
console.log(maomao.run()); // A cat named Maomao is running with the ball of wool...

Copy the code

6. Modifiers:

Three general modifiers:

  • public:publicModification ispublicThe,Can be found inOutside of a classIs access to the.
  • private:privateModification isprivateThe,Only can be inYour own classThe access.
  • protected:protectedModified,Only can be inSubclasses and their own classes“.(It turns the embellished part into a legacy, accessible only to me and my children, but not to anyone else.)

1.publicModifiers: Allow access outside the class

class Person {
    public name:string;
    constructor(name:string) {
        this.name = name; }}const kirk = new Person("krik");
console.log(kirk.name);//ts-node prints -- kirk
Copy the code
  • Examples are availableThe internal nameProperty, if yespublicIf so, thennameWill not be accessible.

aboutsuper:

class Person {
    public name:string;
    constructor(name:string) {
        this.name = name; }}const kirk = new Person("kirk");
console.log(kirk.name);

class Teacher extends Person {
    constructor(public age:number) {
        super("Test the value passed by a subclass to its parent class.")  // Super passes the value to the Person class constructor}}const testName = new Teacher(99);
console.log(testName.age); / / 99
console.log(testName.name);// Tests the value passed by the subclass to its parent
Copy the code
  • And here’s another place to emphasize,classWhen you inherit, you don’t pass values,constructorIn thesuperThat’s for writing, too

2.privateModifiers: Can only be accessed within its own class

/ / private modifiers

class Animal{
  private name:string;
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `}}class Cat extends Animal{
    constructor(name){
        super(name);
        console.log(this.name);   // This is an error due to the private modifier above
        this.name=name;   // Because of the private modifier above, there is an error of +1
    }
    run(){
        return ` a callThe ${this.name}The cat is running around with the ball of wool... `// Because of the private modifier above, there is an error of +1}}Copy the code

3.protectedModifier: onlyoneselfandOne's own childrenaccess

/ / proteted modifier
class Animal{
  protected name:string;      // This place is protected modifier modifier
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `}}class Dog extends Animal{
    // constructor
       constructor(name:string){
          super(name);
          this.name=name;
      }
    run(){
        return `The ${this.name}is swiming~! `}}const dog=new Dog("kirk");
console.log(dog.run());  // Support your own and your children's access, the result is 👇
//kirk is swiming~!

const snake=new Animal("lisin");
snake.name="gogoing"  // An error is reported because of the protected modifier above, now snake. Name can only be accessed from "Animal" and subclasses.
console.log(snake.run()); // lisin is running~!
Copy the code

4.readonlyModifier: read only

/ / readonly modifier
class Animal{
  readonly name:string;
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `}}const snake=new Animal("lisin");
snake.name="gogoing"  // An error is reported because the readonly modifier is used, so it can only be "read", not modified.
console.log(snake.run()); // lisin is running~!
Copy the code

5.staticModifiers :(static methods can be used when the state of the class is unrelated to the instance)

class Animal{
  name:string;
  static categories:string[] = ["Mammals"."Birds"]
    // constructor
    constructor(name:string){
        this.name=name;
    }
    run(){
        return `The ${this.name}is running~! `
    }
    isAnimal(a){
        return a instanceofAnimal; }}console.log(Animal.categories); //[' mammal ', 'bird']

const snake=new Animal("lisin");
console.log(snake.isAnimal(snake)); //true
Copy the code

7.interfaceandimplement:

Extract common logic from the class, put it into an interface, and implement the interface through Implement.

  • throughinterfaceGo and tellCarandcellPhoneYou’re all going to make it happenRadioMethods.
  • interfaceInterfaces can pass through each otherextendsInherited and extended.
  • Class classIs through theimplementsCome to the rightinterfaceFinished use.
/ / interface (1)
interface Radio{
    switchRadio():void
};
/ / interface (2)
interface Battery{
    checkBattery():void
};
  
// Inheritance between interfaces
	// Implement Radio and Barrery methods,inerface can also use extends inheritance
interface RaidowithBattery extends Radio{
    checkBattery():void
};

// The use of the class interface
class Car implements Radio{
    switchRadio(){
        console.log("I'm the SwithRadio method of Car."); }}// implements multiple interfaces
class CellPhone implements Radio.Battery{
    switchRadio(){
        console.log("I am cellPhone's SwithRadio method");
    }
    checkBattery(){
        console.log("I check the battery 🔋")}}class CellPhone1 implements RaidowithBattery{
    switchRadio(){
        console.log("I am cellPhone's SwithRadio method");
    }
    checkBattery(){
        console.log("I check the battery 🔋")}}const pokmen = new CellPhone();
 console.log(pokmen.switchRadio());  // I am cellPhone's SwithRadio method
Copy the code

8. The enumeration:

1.enums:

  • Enumeration is aBidirectional mapping
enum Direction{
    Up,
    Down,
    Left,
    Right
};

//🤖 This two-way access is a bit cheesy
console.log(Direction.Down); / / 1
console.log(Direction[3]);  //Right
Copy the code

2. Understanding of compiled files:

Example 1:
/ / enmus. Ts file
enum Direction{
    Up=10.// When up is set to 10, down, left, and right increment successively
    Down,
    Left,
    Right
};
console.log(Direction.Down);  / / 11
console.log(Direction[13]);  //right
Copy the code

Then execute the command line to compile:

tsc enums.ts
Copy the code

Compiled file:

var Direction;
(function (Direction) {
    Direction[Direction["Up"] = 10] = "Up";
    Direction[Direction["Down"] = 11] = "Down";
    Direction[Direction["Left"] = 12] = "Left";
    Direction[Direction["Right"] = 13] = "Right";
})(Direction || (Direction = {}));
;
console.log(Direction.Down); / / 11
console.log(Direction[13]); //Right
Copy the code
  • Self-executing functions encapsulate one of their ownUnique scope
  • []Within theDirection["Up"]=0Is used forExplain myself, will beDirectionInside the objectUpSet to0;
  • javascriptAssignment returns the value that was assigned to it, so
    • Direction[Direction["Up"] = 10] = "Up", which is equivalent toDirection[10] = "Up";

Example 2:

Compile the front:

//enums.ts
enum Direction{
    Up="UP",
    Down="DOWN",
    Left="LEFT",
    Right="RIGHT"
};
console.log(Direction.Down);  / / 1
console.log(Direction[3]);  //Right
Copy the code

The compiled:

var Direction;
(function (Direction) {
    Direction["Up"] = "UP";
    Direction["Down"] = "DOWN";
    Direction["Left"] = "LEFT";
    Direction["Right"] = "RIGHT";
})(Direction || (Direction = {}));
;
console.log(Direction.Down); / / 1
console.log(Direction[3]); //Right
Copy the code

Example 3:

enum Direction{
    Up="UP",
    Down="DOWN",
    Left="LEFT",
    Right="RIGHT"
};
// console.log(Direction.Down);  // 1
// console.log(Direction[3]); // Right

const value="DOWN";
if(value === Direction.Down){
    console.log("CrossOver~!")}// Print the result
//CrossOver
Copy the code

9. The generic:

1. The generic:

  • Declare generic variables after function names<T>, which is used tocaptureDeveloper passed inThe parameter types(string, for example), and then we can use itT(that is, string) doThe parameter typesandReturn value typethe
// This "<>" thing is generic

function echo<T> (arg:T) :T
{
    return arg;
}

// By type inference T is a string
const result=echo("123");

// Use generics in tuples:
function swap<T.U> (tuple:[T,U]) :U.T]
{
    return [tuple[1],tuple[0]]}const result2=swap(["String".123]);
// Mouse over result2, see result2 type the first is number, the second is string

console.log(result2[1]); / / string
Copy the code

2. Constraint generics:

//1. Restrict generics by adding [] after T
function echoWithArr<T> (arg:T[]) :T[]{        
    console.log(arg.length);
    return arg;
}
const arrs=echoWithArr([23.34.45]);
// The console prints the result: 3
Copy the code
//2. Use interface to restrict
interface IWithLength{
    length:number
};
//🌵 extends in Angle brackets to constrain that the value passed to the function must have the length attribute
function echoWithLength <T extends IWithLength> (arg:T) :T
{
    console.log(arg.length);
    return arg;
}
const o = echoWithLength("sdsfs");
const obj = echoWithLength({length:1005});

console.log(o); / / 5

consple.log(obj);// 1005 {length:1005}
Copy the code
  • Is theInput and outputLimit – only ownlengthAttribute, or an error is reported
    • inTThe back to add[]To achieveConstraints of genericThe effect of
    • throughextends interfaceTo restrict

3. Index generics

We need to design a function that takes two arguments, one an object and the other a property on the object, and returns the value of the property using the two arguments, such as:

function getValue(obj: object, key: string) {
  return obj[key] // error
}
Copy the code

The obj argument is actually {}, so the following key cannot take any value on it.

Here we introduce the index type:

function getValue<T extends object.U extends keyof T> (obj: T, key: U) {
  return obj[key] // ok
}
Copy the code
  • keyofThe incomingobjecttheAttribute typesTake out to generate aThe joint type.

10. Generic applications:

1. There is a problem with the following example. It is impossible to determine whether it can be usedtoFixedMethods:

// Example 1:
class Queue{
    private data=[];
    push(item){
      return  this.data.push(item);
    };
    pop(){
      return  this.data.shift(); }}const queue=new Queue();    / / 💡

queue.push(1);
queue.push("this Love")
console.log(queue);  // Queue { data: [ 1, 'this Love' ] }

console.log(queue.pop().toFixed());/ / 1

console.log(queue.pop().toFixed());// This Love is a string, cannot use toFixed method, error;
Copy the code

2. The best solution:

Constrain the shape of a class by generics 👇 :

class Queue<T>{
    private data=[];
    push(item:T){
      return  this.data.push(item);
    };
    pop(){
      return  this.data.shift(); }}const queue=new Queue<number> ();
       
       
      
queue.push(1);
queue.push("this Love")---- "this Love" cannot be assigned to number

const queue2=new Queue<string> (); queue2.push("pokmeon go!");
console.log(queue2.pop().length);  / / 11
Copy the code

3. Use of generics in interfaces:

// Define the interface
interface KeyValue<T,U>{
    key:T;
    value:U;
}; 
// Use the interface and constrain the interface with generics
let k1:KeyValue<number.string> = {key:920.value:"Small-town girl"
};
console.log(k1);     //{key: 920, value: 'town girl'

let k2:KeyValue<string.number> = {key:"Go ahead, Pikachu!".value:999
};

console.log(k2);     //{key: 'Go ahead, Pikachu ~! ', value: 999 }
Copy the code
  • Numeric array2Kind of writing:
let arr:number[] = [1.2.3.4.5.6];
// Use generics to define arrays
let arr1:Array<number> = [6.5.4.3.2.1];
console.log("I am arr",arr);        I am arr [1, 2, 3, 4, 5, 6]
console.log("I am arr1",arr1);      I am arr1 [6, 5, 4, 3, 2, 1]
Copy the code
// Pass in different generic values for different types 🌵
// Define a generic interface to constrain functions
interface IPlus<T>{
    (a:T,b:T):T;
}

function plus(a:number,b:number) :number{
    return a+b;
}

function connect(a:string,b:string) :string{
    return a+b;
}

const a:IPlus<number>=plus;
const b:IPlus<string>=connect;
Copy the code

Type aliases and type assertions

1. Type aliases:

// Type alias uses 1:

type PlusType = (x:number,y:number) = >number;

function sum(x:number,y:number){
    return x + y;
};

const sum2:PlusType = sum;

Copy the code
// Type alias uses 2:
type NameReslover =  () = > string;
type NameOrReslover = string | NameReslover;

function getName(n:NameOrReslover) :string
{
    if(typeof n === "string") {return n
    }else{
        returnn(); }}Copy the code
Case 2 analysis:
  • First pass type NameReslover =() => string; Made a call type NameOrReslover = string | NameReslover; A rule is a function that returns a string

  • Then through the type NameOrReslover = string | NameReslover; There is a rule called NameOrReslover, which can be either a string or the NameReslover defined above

  • Create a getName function that takes NameOrReslover and returns string.

  • This function, called getName, internally checks whether the argument is of type “string”, returns if it is string, and calls the function if it is not.

  • Be aware of the type aliases above

// Type alias uses 3:
type Directions = "Up" | "Down" | "Left" | "Right"
let toWhere:Directions = "Left";// toWhere is restricted to one of the top, bottom, left, and right
Copy the code

2. Crossover type:

// Cross type examples:
interface IName {
  name:string
}
type IPerson = IName & {age:number}

let person:IPerson = {name:"123".age:123}
Copy the code

Type assertion:

Type assertions are used to tell the compiler that it knows a type better than it does, and that it should not issue an error.

function getLength(input:string | number) :number{
    
  	// General operation
    // const str = input as String;
    // if(str.length){
    // return str.length;
    // }else{
    // const number =input as Number;
    // return number.toString().length;
    // }
  
    // The assertion operation
    if((<string>input).length){ // (
      
       input
      
        return (<string>input).length
    }else{
        returninput.toString().length; }}console.log(getLength(1231231));/ / 7
Copy the code

Override the above method with type Guard:

Type Guard uses instanceof or Typeof to narrow down types

function getLength(input:string | number) :number{
	if(typeof input === "string") {return input.length;
  }else{
    return input.toString().length
  }
}
Copy the code

As you can see, the assertion operation is much cleaner than the normal operation above.

12. Declaration files and built-in types:

1. Declaration Document:

For example using Jquery:

  • Usually put the following declaration in a separate file – jquery.d.ts

  • Declaration files usually end with the file name +.d.ts

declare var jQuery:(selector:string) = > any;
Copy the code

Or by installing the official declaration file:

npm install --save @types/jQuery
Copy the code

For more information about the installation of some third-party libraries, as well as the declaration file, please check the address:

www.typescriptlang.org/dt/search?s…

2. Built-in types:

const a:Array<number> = [1.2.3];
const data = new Date(a); cosnt reg =/abc/
reg.test("abc")

Math.pow(2.2)

let body = document.body;
let allLis  = document.querySelectorAll("li");

Copy the code