Preface: This article is a TypeScript series of articles. Designed to use fragmented time to quickly get started with Typescript. Or to revisit old Typescript gaps. On the basis of the official API, add some impressions of daily use. If you are interested ~ welcome to pay attention to the follow-up continue to launch the article.

List of articles:

  • TypeScript basic types
  • Typescript enumeration
  • 3. Typescript interfaces
  • Typescript generics
  • 5. Typescript functions and classes
  • Typescript type assertions

Directory structure:

  • Function declaration
  • Common error in function declaration
  • Function overloading
  • Class modifier
  • Class declaration common error

Function declaration

To get to the point, here are four ways in which functions can be defined: TypeScript can automatically infer the return value type from the return statement, so we usually omit it.

  1. Declare function parameters directly
function add(x:number, y: number) {
    return x + y;
}
Copy the code
  1. In real development, function calls often use destruct assignment directly, thereby reducing assignment. This scenario is declared as follows:
function add({ x, y }:{x: number, y: number}) {
    return x + y;
}
add({x: 2,y: 3}) 
Copy the code
  1. Declare residual arguments. When used, the residual argument is actually an array. With that in mind, we just need to declare the array format. The code is as follows:
functionadd(... rest: number[]) {return rest.reduce((pre,cur) => pre+cur)
}
add(2, 3, 4, 5)
add('23',3) // error, cannot be a stringCopy the code
  1. In the absence of a function implementation, there are two ways to declare function types:
type add = (x: number, y: number) => number;
interface add {
    (x: number, y: number):number
}
Copy the code

Call as follows:

let addFn:add  = (a, b) => {
    return a + b
}
Copy the code

Common error in function declaration

Mandatory parameters cannot be placed after optional parameters.

// A required parameter cannot follow an optional parameter.
functionadd(x? : number,y: number) {return x + y;
} 
Copy the code

Function overloading

This is a nice feature. Function overloading can be seen in many large libraries. After using it, other people can look at the number of function overloads and see all the functions and branches in the function. The function is overloaded as follows: TS looks for the type at first, returns it if it matches, and goes to the next one if it doesn’t

function add(x: string, y: string): string;
function add(x: number, y: number): number;
function add(x: any, y: any): any{
    if (typeof x === 'string') {
        return 'string';
    } else if(typeof x === 'number') {
        returnx + y; }}Copy the code

For example, look at the following code:

  1. The only key
  2. The key, the config
  3. Pass key, fn, config

Tips: When maintaining a common component, use this method to quickly let users and future maintainers know how the function is called and what the function does.

Class modifier

Class modifiers extend some of the functionality of native JS, which is a nice feature.

class Greeter {
    constructor(message: string) {
        this.greeting = message;
    }
    
    greeting: string;
    readonlyx: number; // Read-only property, cannot be modified publicgreet() {
        return "Hello, " + this.greeting;
    }
    private hello() {
        return 'ee';
    }
    protected hi() {
        return 'ee';
    }
}

class children extends Greeter {
    constructor(m: string) {
        super(m);
    }

    test() { this.hello(); This.hi () cannot be called outside the class. }} new children('333').greet()
new children('333').hello() // New children() is a private member and cannot be called outside the class.'333'Hi () // Error: can only be called in subclassesCopy the code

To summarize the above code:

  1. Private cannot be called by subclasses, cannot be accessed from instances, can only be called from within the declared class
  2. Protected can only be called from a subclass, not an instance
  3. Public can be called.

TypeScript supports intercepting access to object members via getters/setters. It helps you effectively control access to object members.

class Greeter {
    constructor(message: string) {
        this.greeting = message;
    }
    greeting: string;
    get hello() {
        return this.greeting;
    }
    set hi(x) {
        this.greeting = x;
    }
}
const x = new Greeter('eeee')
x.hi('22');
x.hello = '2'// Error reported, cannot be modifiedCopy the code

In effect, getters/setters are used to intercept access to object members. The source code is as follows:

var Greeter = /** @class */ (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Object.defineProperty(Greeter.prototype, "hello", {
        get: function () {
            return this.greeting;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Greeter.prototype, "hi", {
        set: function (x) {
            this.greeting = x;
        },
        enumerable: true,
        configurable: true
    });
    returnGreeter; } ());Copy the code

3. Static properties

Static is a method that can be called directly without using new.

class Greeter {
    constructor() {}
    static config: string = '33';
}
Greeter.config ='3'
Copy the code

Class common error

If the property has declared accessibility in constructor, it need not declare it again below.

class Dog { constructor(public name: string) { // th.is.x = x } name: string; // Error, Duplicate identifier'name'. Repeated declarationeat() {}}Copy the code

conclusion

This article introduces typescript functions and classes. Class modifiers have a wide range of applications. Declaring a class’s private members, public members, and accessors makes third-party calls more secure. Function overloading is also a great help for readability.

  • Welcome to pay attention to “front-end plus”, seriously learn front-end, do a professional technical people…