Because Typescript continues to be popular, let’s share the common knowledge of TS. Let’s learn and communicate together.

The definition of a class

1. The modifier

1. Public stands for public, which can be accessed both internally and externally

2. Protected means protected, only subclasses and themselves can access

3. Private indicates that the IP address is private and only the user can access the IP address

2. Readonly Read-only property

3. Static properties that can be accessed directly using the class

4. Extends to inherit

5. Super represents the superclass and can call the methods of the superclass

class Person {
  // Public property
  public readonly name: string;
  public age: number;

  private id: string = "id";

  protected gender: string = "male";

  public static email: string = "[email protected]";

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  // If you do not want to declare variables before the constructor, you can use the following method
  // constructor(public name: string, public age: number) {
  // this.name = name;
  // this.age = age;
  // }

  protected getName(): string {
    return this.name;
  }

  getAge(): number {
    return this.age;
  }

  setAge(age: number) :void {
    this.age = age;
  }

  getId(): string {
    return this.id; }}class PoliceMan extends Person {
  // Since the name and age are inherited from the parent class, we don't need to declare them
  constructor(name: string, age: number) {
    // Perform the super method to call constructor
    super(name, age);
  }

  private policeNo: string = "11111";

  printId() {
    // The id is private, so an error is reported
    // console.log(this.id)
  }

  printGender() {
    // The gender attribute of the parent class is protected
    console.log(this.gender); }}const person = new Person("Tom".20);
// Public properties can be accessed at will
console.log(person.name); // Tom
// The readonly attribute cannot be copied
// person.name='Cherry';

// Access the static property
console.log(Person.email); // [email protected]"

// Cannot access private properties
// console.log(person.id)
// If you want to access only through the internal method
console.log(person.getId()); // id

const policeMan = new PoliceMan("David".30);

// If you want to access the protect property of the parent class, you can only access it from the calling method
console.log(policeMan.printGender());
// Access the static methods of the parent class
console.log(PoliceMan.email);

Copy the code

A decorator

A decorator is a special type of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

Decorators use the form @expression. Expression must be evaluated to be a function that is called at runtime, passing in the decorated declaration information as an argument

Note: To use decorators, you must set experimentalDecorators to true in tsconfig.json

“compilerOptions”: {

“experimentalDecorators”: true,

}

1. Class decorator

The constructor of a class is its only argument

// Return a new class via the class decorator
function classDecorator(constructor: Function) {
    return class {
        name: string = "David";
        age: number = 11;
    };
}

@classDecorator
class Animal {
    name: string = "Tom";
}

const animal = new Animal();
// The default derivation of ts is not available, so the assertion is used to enforce it
console.log((animal as any).age); / / 11

function classDecoratorFactor(name: string) {
    return function (constructor: Function) {
        constructor["gender"] ="male"; // This is equivalent to copying the static of the class
        // Copy the name on the prototype chain for the object
        constructor.prototype.name = name;
        // Add the setName method to the prototype chain of the object
        constructor.prototype.getName = function () :string {
            return name;
        };
    };
}
// Type decorator factory
@classDecoratorFactor("River")
class Person {
    static gender: string;
    name: string;
    getName(){}}const person = new Person();
console.log(person.name); //River
console.log(person.getName()); //River
console.log(Person.gender); //male
Copy the code

Method decorators

Decorates the method and returns a value of

1. Class constructors for static members, prototype objects for instance members.

2. Names of members.

3. Attribute descriptors for members.

function decoratorMethod(str: string) {
    return function (proto: any, key: string, descriptor: PropertyDescriptor) {
      // Override the method
      descriptor.value = function () {
        return str;
      };
    };
  }

class SaleMan {
    @decoratorMethod("women")
    say() {
        // console.log("I am sale man ");}}const saleMan = new SaleMan();
console.log(saleMan.say());
Copy the code

4. Property decorators

Decorates the method and returns a value of

Class constructor for static members, prototype objects for instance members. *

2. Names of members.

function decoratorProperty(str: string) {
    return function (proto: any, key: string) :any {
      const descriptor: PropertyDescriptor = {
        writable: true}; proto[key] = str;return descriptor;
    };
  }

  class BusinessMan {
    @decoratorProperty("BusinessWoman")
    name: string;
  }

  const businessMan = new BusinessMan();
  // Get the name on the prototype
  console.log((businessMan as any).__proto__.name);

Copy the code

5. Parameter decorators

Decorates the method and returns a value of

Class constructor for static members, prototype objects for instance members.

2. Names of members.

3. The index of the parameter in the function parameter list.

function addAge(target: any, propertyKey: string, paramIndex: number) {
    console.log(propertyKey)
    console.log(paramIndex)
  }

  class Person2 {
    // Parameter decorator
    showName(@addAge name: string){}}const person2=new Person2();
  person2.showName('Dannie');// Print showName and
Copy the code

The relevant data

  • The TypeScript’s official website

If you like it, check out my column (TypeScript common knowledge). I will try to keep it updated every night. If you like it, please give me a like

If you like “algorithm”, you can check out another column I shared (front-end algorithm), which has more problems about the algorithm to share, hope to help you deeper understanding of the algorithm

The purpose of this article is to study, discuss and share the experience in the process of learning algorithm. Part of the material in this article comes from the network. If there is infringement, please contact delete, [email protected]