-07- function of the type of foundation TypeScript-

Type function

JavaScript functions are first-class citizens

Function declarations

In JavaScript, there are two common ways defined function - a function declaration (Function Declaration) expression and function (Function Expression):

// 函数声明(Function Declaration)
function sum(x, y) {
    return x + y;
}

// 函数表达式(Function Expression)
let mySum = function (x, y) {
    return x + y;
};

A function input and output, to be TypeScript constraints, it is necessary to take into account both the input and output, wherein the function type definition statements is relatively simple:

function sum(x: number, y: number): number {
    return x + y;
}

Note that, enter extra (or less than required) parameters, it is not allowed :

function sum(x: number, y: number): number {
    return x + y;
}
sum(1, 2, 3);

// index.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target.
function sum(x: number, y: number): number {
    return x + y;
}
sum(1);

// index.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target.

Function expression

If we now want to write a definition of the function expression (Function Expression) may be written like this:

let mySum = function (x: number, y: number): number {
    return x + y;
};

This is can be compiled, but in fact, the above code only to an anonymous function on the right side of the equal sign were type definitions, and the left side of the equal sign mySumis an assignment by operation type inference and inferred. If we need to manually mySumadd the type, then it should be like this:

let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
    return x + y;
};

Be careful not to confuse the TypeScript =>and ES6 in =>.

Definition of the type of TypeScript, =>used to represent the function definition, the left input type is required parentheses, right is the output type.

In the ES6, =>called the arrow functions, is widely used, can refer to [the ES6 arrow function] [].

The shape of the interface defined function

We may also need to define the shape of a function in line with the use of the interface:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}

Optional parameters

As mentioned earlier, the extra input (or less than required) parameters, is not allowed. So how do you define optional parameters?

Similar optional attributes interface, we ?denote optional arguments:

function buildName(firstName: string, lastName?: string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        return firstName;
    }
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');

Note that the optional parameter must be connected after the required parameters. In other words, behind the optional parameters are no longer allowed the required parameters :

function buildName(firstName?: string, lastName: string) {
    if (firstName) {
        return firstName + ' ' + lastName;
    } else {
        return lastName;
    }
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName(undefined, 'Tom');

// index.ts(1,40): error TS1016: A required parameter cannot follow an optional parameter.

Parameter Default

In ES6, we allow the parameter to the function add default values, the typescript will add parameters to identify the default values for the optional parameters :

function buildName(firstName: string, lastName: string = 'Cat') {
    return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');

At this point it is not "optional parameters must be connected to the back of the required parameters" of the restrictions:

function buildName(firstName: string = 'Tom', lastName: string) {
    return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let cat = buildName(undefined, 'Cat');

For the default parameters, reference may be [ES6 default values ​​in the function parameters] [].

The remaining parameters

ES6 may be used ...restembodiment acquires the remaining parameters (rest parameter) function:

function push(array, ...items) {
    items.forEach(function(item) {
        array.push(item);
    });
}

let a = [];
push(a, 1, 2, 3);

In fact, itemsan array. So we can use it to define the type of the array:

function push(array: any[], ...items: any[]) {
    items.forEach(function(item) {
        array.push(item);
    });
}

let a = [];
push(a, 1, 2, 3);

Note, rest parameters can only be the last argument, rest on the parameters, refer to [rest parameters ES6] [].

Overload

When overloading allows a function to accept a different number or type of parameters to different treatment.

For example, we need to implement a function reverse, enter the number 123when the inverted digital output 321, the input string 'hello'when output reversed string 'olleh'.

The use of joint types, so we can achieve:

function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

However, this has the disadvantage that can not be accurately expressed, the digital input, the output should be a number, a character string input, the output should be a string.

At this time, we can use to define multiple overloaded reversefunction type:

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

The above example, we define a number of repeat function reverse, all previous function definition, is a function of the last implementation. Code hints in the editor, you can see the correct first two tips.

Note, TypeScript will give priority to start match-defined functions from the front, so if you have more than one function defined containment relationship, you need to give priority to precise definition EDITORIAL.

Guess you like

Origin www.cnblogs.com/idspring/p/11784710.html