TS learning notes

Posted by donbre on Tue, 18 Jan 2022 10:12:03 +0100

1, Data types in Ts

Before introducing data types, first explain the declaration and assignment methods in ts.
1) Declare first and assign value when necessary:

let c:number;
c=5

2) Direct assignment after declaration

let c:boolean = true;

3) After direct assignment, the variable type defaults to the type at the first assignment and cannot be changed again

  let c=5//Equivalent to let c:number=5;

1. number type

Double precision 64 bit floating point value. It can be used to represent integers and fractions.

2. boolean.

Indicates logical values: true and false.

3. String string type

A character series that uses single quotation marks (') or double quotation marks (") to represent a string type. Back quotation marks (`) define multiline text and embedded expressions.

4. Array type:

Declare variables as arrays.

let arr: number[] = [1, 2];
let arr: Array<number> = [1, 2];
let arr: (number | string | number[] )[] = [1, '4', [1, 2, 4]]

5. Tuple type

For an array with known number and type of elements, the type of each element does not have to be the same, and the type of the corresponding position needs to be the same.

   let x: [string, number]=['hello',1]

6. Enumeration type: defines a collection of values.

   enum Color{Red,Green}
   let i:Color=Color.Red

7. any type

Variables declared as any can be given any type of value, which is equivalent to turning off type checking

   Explicit: let a:any;
   Implicit: let a;

8. Unknown unknown type

The difference between it and any is that when any type variable is used to assign other values, other values will become any, while unknown cannot be assigned to other values. Type check must be carried out before assignment

let a:unknown;
let b:string;
if(typeof a ==='string')
{
    b=a
}

9. null: defined and empty value

10. Undefined: undefined value

11. Never never appears

It can only be assigned by a value of type never.
If the return value of the function is set to it, you can throw an exception or fail to execute to the termination point (such as an infinite loop)

function fn():never{
    throw new Error('Empty')
}

12. Void: indicates null. Null also exists. This is the difference between void and never.

13. object: the form of a key value pair.

① Can be declared directly with js

let Obj={
    a:'111'
}

② First, describe the attributes and types of the object in the object format:

let obj={
    a:sting
}
obj={
    a:'abc'
}

Note that if you first describe the properties and types of the object,
When creating this object, you must strictly follow the property type represented by the declaration
③ The type declaration limits the object structure, which is similar to ②, but the writing method is slightly different.

type myType= { 
        firstName:string, 
        lastName:string, 
           sayHi(): string 
        } 
let obj:myType={
        firstName:'string', 
        lastName:'string', 
        sayHi():string{
            return 'ss'
         } 
}  

④ Interface type limit object structure

interface myInterface= { 
    firstName:string, 
    lastName:string, 
       sayHi(): string 
    } 
let obj:interface={
    firstName:'string', 
    lastName:'string', 
    sayHi():string{
        return 'ss'
     } 
 }               

③ If there is an attribute whose existence is uncertain, you can add?, after the attribute?, Eg:

let c:{
    name: boolean,
    age?: number
}

④ When the number of attributes is uncertain

  let c:{
            [propName:string] : any
        }

14. Function:

Basic syntax: limit the return value type and parameter type of a function

function fn(a:number,b:number): void{
}

Syntax under various parameters:
① If the parameter type is determined but the number is uncertain, the remaining parameter syntax can be used:

 function fn(a:number[]){ } At this time, the parameter is passed in as an array

② A limited number of parameters cannot determine whether they will exist:

 function fn(a:number,b?:string){ } Add "yes" before this parameter? Modifier 

③ The defined function does not determine the parameter type / return value type, but determines the number

function fn<T>(a:T):T{return a } 

The meaning of this function is to pass in parameter a and return A. among them, it indicates that the generic name is T. after the function is declared, it can be called directly. If the generic actual value is not declared, ts will judge automatically, but it is not rigorous. It is better to specify it.

Unspecified call: fn(5) / Specify call fn<number>(55)

You can also specify multiple generics at the same time, Eg:

   function fn<T,K>(a:T,b:K):T|K{}

The return value of the function is represented by | and the return value type can be T or K
Function overload:
1. The number, type or order of parameters of a function with the same name must be different (one of which satisfies the condition) is called function overloading
2. Overloading allows a function to accept different numbers or types of parameters and make different processing. Provide multiple function type definitions for the same function for function overloading
When defining overloads, be sure to put the most accurate definition first. Because when searching the overload list, it will be used from the first overload definition. If the match is successful, it will be used. Otherwise, continue to look down; Finally, when implementing the function, you need to use the | operator or? Operator, including all possible input types (if not, you can write any)
3. The meaning of function overloading is to let you know that different type parameters can get different type results. If the parameters are different, but the results (types) are the same, function overloading is not required here

15. Scattered knowledge points

1. The value can be expressed by | let a:1|2; Basic types make sense
2. The value can be expressed as & let a: {Name: String} & {age: number} is used for the object
3. Alias the type:

type myType=1|2|3;
   let a:myType;

4. Type assertion: allows variables to be changed from one type to another.
Syntax: < type > value
Value as type

2, Class

TypeScript is object-oriented JavaScript, which describes the common properties and methods of the created objects.

1. Basic syntax:

   class c{
          attribute:type,Eg: name:string;
          Constructor,Eg: constructor(name:string){
              this.name=XXX
          }
          method,Eg: dis():void{
              console.log(123)
          }
          Static properties/method: static age:number=1
                         static fn():void{
                             console.log(11)
                         }
          Read only attribute/method: randonly 
          static state+Read only: static randonly name:number=18;
      }

Static attribute: adding static before the attribute / method indicates that the attribute is a static attribute (class attribute)
Read only attribute: adding static before the attribute / method indicates that the attribute is read-only and cannot be modified

2. Class inheritance

1. Class inheritance uses the keyword extends. Subclasses can inherit everything except the private members (Methods and properties) of the parent class.
2. Inheritance can write the common code of multiple classes in a parent class. If a child class wants to write some additional methods and properties, it can be added directly.
3. The method with the same name of the subclass will override the method of the parent class
4. A subclass can inherit only one parent class
When adding additional attributes to a subclass, you need constructor() and must add super(), which means calling the constructor of the parent class, and the super() parameter is the attribute value of the parent class
If the constructor() is not written in the subclass, the property value of the parent class will be passed in as a parameter when new comes out of the new object

class Animal {
            name: string;
            age: number;
            constructor(name: string, age: number) {
                this.name = name
                this.age = age
            }
            eat(): void {
            console.log('animal')
            }
                }
        class cat extends Animal {
              eat(): void {
                console.log('cat')
            }
            xixi: string;
            constructor(xixi: string) {
                super('cat', 5)
                this.xixi = xixi
             }
            }
        var xiaoxiao = new cat('Meow meow~')

3. Abstract class

When a class only wants it to be inherited as a superclass without directly using it to create objects, add abstract to make it an abstract class.

abstract class Animal{
            name:string;
            age:number;
            constructor(name:string,age:number){
                this.name=name
                this.age=age
            }
          abstract eat():void{}
         }   

Abstract methods can only be created in abstract classes and have no method body. Subclasses are required to override them

Encapsulation of attributes in class

Access control characters can be used to protect access to classes, variables, methods and constructor methods. There are three kinds of modifiers:
1.public (default): public, which can be accessed anywhere.
2.protected: protected and can be accessed by itself and its subclasses.
3.private: private, which can only be accessed by the class where it is defined.

 class Encapsulate { 
                 public str1:string = "hello" 
                 private str2:string = "world" 
                 protected str3:string='hi'
                 public fn():void{
                      console.log(this.str2)
                }
            }
            class children extends Encapsulate{
              fn():void{
                 console.log(this.str1,this.str3) //Accessible
                 console.log(this.str2) //Compilation error, str2 is private
                  }
            }
            var objs = new Encapsulate() 
            var child=new children()
            child.fn()
            console.log(objs.str1)     // Accessible 
            console.log(objs.str2)   // Compilation error, str2 is private
            console.log(objs.str3)   // Compilation error, str3 is protected

Note: for the attribute / method with the protected modifier, although the subclass can be accessed, the instantiated object cannot be accessed
Private properties can be exposed through public methods.
4. Getter and setter in class: properties can be modified and called through getter and setter methods (private and protection are also applicable)

   class Encapsulate { 
            public _str1:string = "hello" 
            private _str2:string = "world" 
            protected _str3:string='hi'
            get str2(){
                return this._str2
            }
            set str2(a:string) {
                if(a=='555'){
                    this._str2= a
                }else{
                    this._str2=this._str2
                }  
            }
        }
        var objs = new Encapsulate() 
        objs.str2='555' //It is equivalent to that the parameter on the right of = is set, which can realize the assignment judgment before attribute assignment
        console.log(objs.str2)//The direct punctuation rule is equivalent to calling the get method

Note: don't duplicate the names of get set and its own attributes, and this method only exists above es5.
In actual development:
get method to set complex properties, that is, properties related to other properties in the class
set method is called to judge - > modify its own attributes when its own attributes are related to some attributes of other classes.

3, Interface

An interface is a declaration of a series of abstract methods and a collection of method features. These methods should be abstract and need to be implemented by specific classes.

interface IPerson { 
    firstName:string, 
    lastName:string, 
    sayHi: ()=>string /sayHi(): string Same meaning 
} 

All attribute methods in the interface cannot have definite values. It is very similar to the type declaration, except that it is a keyword interface name, {} and the type declaration is a keyword type name = {}

  type myType= { 
                firstName:string,  
                sayHi(): string 
            } 
        interface myInterface{ 
                firstName:string, 
                sayHi(): string 
            } 

In addition, the interface can be declared repeatedly to finally take the collection; The interface declaration is not allowed. It can only be declared once.
An interface is similar to an abstract class. All its values cannot have actual values, that is, its methods are abstract methods. The class implements the syntax format of the interface:

   class myClass implements myInterface{
                    firstName:string
                    coonstructor(firstName:string){
                        this.firstname=firstname
                    }
                    sayHi():string{
                        return 'Hi'
                    }
                }

The interface is unique to Ts and will not be reflected in the compiled Js file.
Interface inheritance means that an interface can extend itself through other interfaces. Typescript allows interfaces to inherit multiple interfaces.

4, Generics

A broad type, usually used for classes and functions
See ts function type for generic types in functions.
In addition, generics can specify interfaces / classes

interface my{
lengths:number
}
function func<T extends my>(a:T):number{
    console.log(a.lengths,'HHH')
    return a.lengths
}
func({lengths:5})
When the generic type corresponding to the parameter of the function specifies the interface, remember to pass the parameter as an object when calling this function,The same is true when a generic type specifies a class
class bb {
 name: string
    constructor(name: string) {
        this.name = name
    }
       }
function func<T extends bb>(a: T): string {
    console.log(a.name, 'HHH')
    return a.name
}
func({ name: '55' })

Generics in a class: when the type of an attribute in a class is uncertain, use generics when declaring it, and pass in the desired type when instantiating an object.

class myClass<T>{
    name:T
    constructor(name:T){
        this.name=name
    }
}
const mc=new myClass<string>(name:'Xiao Sun')

Topics: Javascript Front-end TypeScript