TypeScript reinterprets

Recently, I also began to learn the knowledge points behind Ts. Bean sprout also summarized here to deepen his impression. Speaking of the advanced knowledge of Ts, we will first talk about the INTERFACE of Ts.

Interface (Interface)

Interfaces function like abstract classes, except that all methods and attributes in an interface have no real values. In other words, all methods in an interface are abstract methods. An interface is responsible for defining the structure of a class. An interface can restrict the interface of an object. An object can only match the interface if it contains all the attributes and methods defined in the interface. At the same time, you can have a class implement an interface that protects all properties in the interface.

    interface Person{
        name: string;
        sayHello():void;
    }
    
    function fn(per: Person){
        per.sayHello();
    }
    
    fn({name:'Cao Bean sprouts'.sayHello() {console.log(` Hello, I amThe ${this.name}`)}});
    
Copy the code

Interface properties

Read-only state (readonly)

interface beanSprouts {
    readonly name: string
}

let bean: beanSprouts = {
    name: 'Cao Bean sprouts'
}

bean.name = 'Bean sprouts' // The bean is in a readable state and cannot be assigned
Copy the code

Optional state (?)

interface beanSprouts {
    name: string, age? :number
}

let bean: beanSprouts = {
    gender: 'Cao Bean sprouts'
    // The age attribute is not assigned at this time because beanSprouts are optional
    // When we don't have to set the object to a certain value, we can use? To indicate that the current property is optional
}
Copy the code

Description attribute

interface beanSprouts {
    height: number;
    width: number;
    [propName: string] :number// At this point all attributes are of type number and key is of type string
}
Copy the code

Inheritance (extends)

Inheritance is used to introduce the provisions of the parent interface into the current interface

interface bean {
    height:number;
}

interface beanSprouts extends bean {
    name: string;
    age: number;
}

let sprouts: beanSprouts = {
    age: 22.name: 'Cao Bean sprouts'.height:188// Add height to the sprouts initialization attribute
}
Copy the code

Class use interface

interface beanSprouts{ name: string; sayHello():void; } class bean sprouts {constructor(public name: string) {} sayHello() {console.log(' console.log '+ this.log); }}Copy the code

So with interfaces out of the way, let’s talk about Generic

Generics (Generic)

The generic definition

Generics can come into play when defining a function or class in situations where the exact type to be used is uncertain (the types of return values, parameters, and attributes are uncertain).

function beanSprouts(arg: any) :any{
   return arg;   
  // Using any causes the function to accept arg arguments of any type, thus missing some information: the type passed in should be the same as the type returned. If we pass in a number word, we only know that any type of value can be returned.
  // Now the beanSprouts function has an undetermined parameter type. To make the type of the return value of a function the same as the type of the argument, we can use generics,
}
// Use generics
function beanSprouts<T> (arg: T) :T{
    return arg;
}

// Use the generics above
// There are two ways to use generics
// Use it directly
beanSprouts(22);
// Define type usage
beanSprouts<number> (22);


Copy the code

We can also define multiple generics at the same time

function beanSprouts<T.K> (age: T, name: K) :K{// Use multiple generics separated by commas
   return name;
}
      
test<number.string> (22."Cao Bean sprout");
Copy the code

Generic constraint

function beanSprouts<T> (age: T) :number{
    return age.length;// Now the length attribute will report an error
 }


// We need to implement an interface so that the generic type has this property, so that it does not report errors.
interface bean{
   length: number;
}
      
function beanSprouts<T extends bean> (age: T) :number{
    return age.length;// Uses extends to specify inheritance relationships for generic types
 }
Copy the code

Classes use generics

class beanSprouts<T>{ prop: T; constructor(prop: T){ this.prop = prop; }}Copy the code

Class (class)

The definition of a class

Classes can be thought of as models of objects.

 classThe name of the class{attribute name: type;constructor(Parameter: Type){
    	this. Attribute name = parameter; } Method name (){.... }}/ / case
class beanSprouts{
  name: string;
  age: number;
    
  constructor(name: string, age: number){
     this.name = name;
     this.age = age;
   }
    
   sayHello(){
     console.log('Hello, I amThe ${this.name}`); }}/ / use
const bean = new Person('Cao Bean sprouts'.22);
bean.sayHello();
Copy the code

inheritance

class beanSprouts{
     name: string;
     age: number;
        
     constructor(name: string, age: number){
        this.name = name;
         this.age = age; }}class bean extends beanSprouts{
        
     learn(){
       console.log(`The ${this.name}Studying ts! `); }}const bean = new learn('Cao Bean sprouts'.22);
bean.learn();
Copy the code

The modifier

Ts attributes have three modifiers:

- public (default), which can be modified in classes, subclasses, and objects - protected, which can be modified in classes and subclasses - private, which can be modified in classesCopy the code

public

class Person{
      public name: string; // Write or write nothing is public
      public age: number;
  
      constructor(name: string, age: number){
          this.name = name; // Can be changed in the class
          this.age = age;
      }
  
      sayHello(){
          console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{
      constructor(name: string, age: number){
          super(name, age);
          this.name = name; // Subclasses can be modified}}const p = new Person('Cao Bean sprouts'.22);
  p.name = 'Bean sprouts';// Can be modified by object
Copy the code

protected

class Person{
    protected name: string;
    protected age: number;

    constructor(name: string, age: number){
        this.name = name; // It can be modified
        this.age = age;
    }

    sayHello(){
        console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{

    constructor(name: string, age: number){
        super(name, age);
        this.name = name; // Subclasses can be modified}}const p = new Person('Cao Bean sprouts'.22);
p.name = 'Bean sprouts';// Cannot be modified
Copy the code

private

class Person{
    private name: string;
    private age: number;

    constructor(name: string, age: number){
        this.name = name; // It can be modified
        this.age = age;
    }

    sayHello(){
        console.log('Hello, I amThe ${this.name}`); }}class Employee extends Person{

    constructor(name: string, age: number){
        super(name, age);
        this.name = name; // Cannot be modified in subclasses}}const p = new Person('Cao Bean sprouts'.22);
p.name = 'Bean sprouts';// Cannot be modified
Copy the code

Class read-only property

If you add a readOnly to the property declaration, the property becomes read-only and cannot be modified

Class property accessor

  1. For properties that do not want to be arbitrarily modified, you can set them to private

  2. Making it private directly will make it impossible to modify its properties through objects

  3. We can define a set of methods in a class that read and set properties, called accessors for properties

  4. The methods that read properties are called setter methods, and the methods that set properties are called getter methods

    class beanSprouts{
          private userName: string;
            
          constructor(name: string){
              this.userName = name;
           }
            
           get name() {return this.userName;
            }
            
            set name(name: string) {this.userName = name; }}const bean = new beanSprouts('Cao Bean sprouts');
       console.log(bean.name); // Read the name property through the getter
       bean.name = 'Bean sprouts'; // Modify the name property with setters
    Copy the code

Static attributes

  1. Static properties (methods), also known as class properties. You don’t need to create an instance with static attributes; you can use them directly from the class

  2. Static properties (methods) start with static

class beanSprouts{
    static PI = 3.1415926;
    static sum(num1: number, num2: number){
        return num1 + num2
    }
}

console.log(beanSprouts.PI);
console.log(beanSprouts.sum(123.456));
Copy the code

this

In a class, use this to represent the current objectCopy the code

At this point, this article is also the end, the bean sprouts behind will be for advanced knowledge to learn and summarize, the latest summary will be synchronized with my public number, interested can also pay attention to see.