Ts

Basic types of

1. Boolean type Boolean

let flag: boolean = false

2. Number type Number

let a: number = 123

3. String type String

let str: string = 'this is string'

4. Array type Array Can be defined in two ways

(1) the first one

Let arr: number[] = [1,2,3,4]

Receive an array whose elements are object types (actual development)

let arr1: {id:string,name:string}[]

(2) The second type (generic)

Let arr: Array<number> = [1,2,3,4]

A tuple is a type that defines each element in an array

Let arr: [string,number, Boolean] = [' string ',123,false]

6. Enumeration Type Enum

The format defined:

Enum Enumeration name {identifier [= integer constant], identifier [= integer constant],... Identifier [= integer constant],};

Applies to parameter mapping representation identification status codes

0 not paid 1 paid 2 successful transactionCopy the code

enum Flag {success=1,error=-1} let f: Flag=Flag.success

Enumeration values defined are values that can be assigned default values. If no value is assigned, default values start from the underlying value. If the value is assigned, the value is washed to an initial value

Eg:

enum Color {red,blue=5,orange} let c: Color = Color.red let o: Color = Color.orange

Print c is 0 and O is 6

7. Any type

Use to add styles to Dom nodes

let oBox: any = document.getElementById('html)

8. Null and undefined(subtypes of other types (never))

Error writing red

var num: number; Console. log(num) output undefined this will float red

Correct term

var num: undefined; Console. log(num) outputs undefined this does not float red

Everyday notation: a notation variable definition that exists or does not exist but is not assigned

var num: number | undefined | null

9. Void means that a method does not return any type

Function run(): void{console.log(' nothing returns ')}

10. The never type is a subtype of the other types (null and undefined) that represents values that never occur

Variables declaring never can only be assigned by type never eg:

var a: undefined; A =123 var b: null; B =123 b=123

Generally used to throw exception errors

A :never a=()=>{throw new Error(' Error ')})()

The definition of a function in Ts

The first: both the input parameter and the return value have defined types

1. Set optional parameters

function run (name:string,age? :number):string{return 'string'}Copy the code

Age can pass or not pass? This parameter is optional

Configure optional parameters Optional parameters must be placed at the end of !!!!

2. Set default parameters

Function run (name:string,age:number=20):string{return 'string'}Copy the code

The age argument can still be passed on the call, in which case the effective value is the one passed in

  1. Configuring Remaining Parameters
function run (... Result :number[]):string{return 'string'} or function run (a:number,b:number... Result :number[]):string{return 'string'} run(1,2,3,4,5) a is 1, b is 2 and the rest is for resultCopy the code

4. Function overloading Same as (name function) a function passing in different parameters to achieve different functions

  function getInfo(name: string): string;
  function getInfo(age: number): number;
  function getInfo(str: any): any{
   if(typeof str === 'string'){
        return `${str}`;
     }eles{
        return str;
     }
   }
   
   getInfo(20)
Copy the code

Definition of a class in Ts

Define a class

class Person{ name: string; Constructor (n: string){constructor(n: string){this.name=n; } run(): void{console.log(this.name)}} var p = new Person(' trisson '); P.run () // Print the followingCopy the code

Inheriting a class

class Person{ name: string; Constructor (n: string){constructor(n: string){this.name=n; } run(): void{console.log(this.name)}} String){// super must have super(name) // Use the constructor method to call the parent class and pass the name to initialize the parent class constructor}} var w = new Web(' li si ') w.ren () // Print li SICopy the code

Subclasses can also implement their own methods

If there’s a method in a subclass that has the same method as the parent class then you execute the method in the subclass and you check to see if you have the method and if you don’t find the method on your parent class then you look in the parent class

Class modifiers (public by default)

Public: public accessible outside the current class, subclass, and class

Protected: Within the current class, accessible within the subclass but not outside the class

Private: private is accessible within the current class, but not outside the subclass

Static properties Static methods

Properties and methods that are mounted directly to the class itself are accessed by the class itself rather than after instantiation

Eg (Es5) :

Function Person(){this.run1=function(){console.log(' Not a static method, }} person.run2 = function(){console.log(' static methods ')} person.name = 'static properties' // Access static properties and method person.name // print static properties Person.run2() // Prints static methodsCopy the code

Eg (ts write static methods and static properties. Static methods can’t call a property of a class directly. If you want to access a property of a class from a static method, you need to define a static property.)

class Per{ public name: string; public age: number=20; Static sex='男' // Static attribute constructor(name: string){this.name=name; } run(){console.log(' instance method ')} static print(){console.log(per.sex,' access static properties ') console.log(' static method ',this.name) // }} var p = new Per(' input ') Per. Print ()Copy the code

Polymorphism (where a parent class defines a method and does not implement it, but lets its subclasses implement it, each of which behaves differently) is a form of inheritance

Eg:

Class Animal{name: string; constructor(name: String){this.name=name} eat(){console.log(' eat method ')}} class Dog extends Animal{constructor(name: constructor) string){ super(name); }} class extends Animal{constructor(name: string){constructor(name: string){super(name); } eat(){return this.name+' eat fish '}}Copy the code

Abstract classes (use the abstract keyword to define abstract classes)

An abstract class in TS is a base class that can be inherited from other classes and cannot be instantiated directly. It is used to define the standard in the class from which it is inherited (for example, in the previous example, the subclass that inherits it may not have the eat method but must have the abstract method if it is an abstract class).

The abstract keyword is used to define an abstract class and an abstract method. Abstract methods in an abstract class contain no concrete implementation and must be implemented in a derived class

Abstract methods can only be placed in abstract classes

Eg:

abstract class Animal{ name: string; constructor(name: string){ this.name = name; } abstract eat(): any; } // This method extends Animal{constructor(name: string) {super(name); // This method extends Animal{constructor(name: string) {super(name); } eat(){return this.name+' eat bones '; }} class constructor extends Animal {constructor(name: string){super(name); } eat(){return this.name+' eat fish '}}Copy the code

Ts interface

The interface in TS is a specification and the specification that defines behavior and actions is a standard

1. Attribute interfaces

The argument that the function passes in is an object and it puts a constraint on the object that’s passed in and it puts a constraint on the method in batch

Function printInfo(labelInfo:{label: string}):void{console.log(labelInfo,' the argument passed in is the object type ')}Copy the code

This example is an input parameter specification for a function and if you have multiple function input parameters that are the same specification then you need an interface to define that

Eg attribute interface:

Interface FullName{firstName: string; // semicolon end lastName: string; Function printName(name:FullName){console.log(name.firstname +'--'+ name.lastname)} var obj = {age:20, FirstName: 'zhang ', lastName: PrintName ({age:20, firstName: {age:20, firstName: {age:20, firstName: {age:20, firstName: {age:20, firstName: {age:20, firstName: 'zhang ', lastName:' 3 '})Copy the code

2. Optional attribute interface

Eg Optional attribute interface:

Interface FullName{firstName: string; // the semicolon ends lastName? : string; Function printName(name:FullName){console.log(name.firstname +'--'+ name.lastname)} FirstName: 'zhang ',})Copy the code

3. Function type interface

Constrain the parameters passed to the method as well as the return values

Eg function type interface:

interface encrypt { (key: string,value: string):string; } const md5:encrypt = function(key: string, value:string): string{ return key+value; } console.log(md5('name',' zhang SAN '))Copy the code

4. Indexable interfaces (object/array constraintsNot commonly used)

1. Constraints on indexable arrays

Eg:

Interface UserArr{[index: number]: string // Indicates the index value of the array. UserArr = [' sub1 ',' sub2 '] console.log(arr[0])Copy the code
2. Constraints on objects that can be indexed

Eg:

Interface UserObj{[index: string]: string // indicates an object} var arr1: UserObj = {name:' zhang 3 '}Copy the code

5. Class type interfaces are constraints and abstractions on a class that must implement properties and methods

Implements this keyword

// Define a class interface Animal{name: string; eat(str: string): void; } // class Dog implements Animal{name:string; constructor(name: string){ this.name = name; } // eat(){console.log(this.name + 'eat bone ')}} var d = new Dog(' little black ') d.eat()Copy the code

An extension of an interface can inherit from an interface

eg:

// Define a parent class interface Animal{eat():void; } interface Person extends Animal{work(): void; } // create a parent class Programmer {name: string; constructor(name: String){this.name=name} coding(code:string){console.log(this.name+code)}} // Inherits the parent class and implements the Person interface class Web extends Programmer implements Person{ constructor(name: string){ super(name); } eat(){console.log(this.name+' eat ')} work(){console.log(this.name+' write code ')}} var w = new Web(' little li ') w.eat(); W.coding (' Write TS code ')Copy the code

Ts generic

Generics address the reusability of class interface methods

1. Generic functions

Generic representation and the keyword T is used to represent exactly what type is determined when this method is called and the parameter that is passed in is the same type as the parameter that is returned

eg:

function getData<T>(value: T):T{
 return value;
}
// 调用
getData<number>(123)
Copy the code

2. A generic class

eg:

Class MinClass<T>{public list:T[]=[]; add(value:T){ this.list.push(value); } min():T{ var minNum=this.list[0]; for(var i=0; i<this.list.length; i++){ if(minNum>this.list[i]){ minNum=this.list[i]; } return minNum; Var m1 = new MinClass<number>() var m1 = new MinClass<number>(); m1.add(2); console.log(m1.min())Copy the code

3. Generic interfaces

1. Eg:

inetrface Config{ <T>(value:T):T; } var getData:Cofig = function<T>(value:T):T{ return value; } getData<string>Copy the code

2. Eg:

inetrface Config<T>{ (value:T):T; } function getData<T>(value:T):T{ return value; } var myGetData:Config<string>=getData; MyGetData ('20') // correctly called myGetData(20) // incorrectly called myGetData(20)Copy the code

4. Generic classes that use classes as parameter types

It’s a messy way to write it

class User{
  username:string | undefined;
  password:string | undefined;
}

class MysqlDb{
 add(user: User):boolean{
   return true;
 }
}

var u = new User();
u.username='kk';
u.password='123456';
var Db = new MysqlDb();
Db.add(u)

Copy the code

Eg: What is the normal way of writing?

class MysqlDb<T>{ add(info:T):boolean{ return true; } class User{ username: string | undefined; password: string | undefined; } var u = new User(); U.user name=' 123 'u.password='123 '; var Db = new MysqlDb<User>(); Db.add(u) // correct db. add(' GHHHH ') // incorrectCopy the code