TypeScript novelty-function

Keywords: Javascript TypeScript

Functions are first-class citizens of JavaScript, where functions can implement abstraction layers, simulation classes, information hiding, modules, and so on.TypeScript extends the functionality of functions on a certain basis.

Function type

Function return value type

We can add a type to each parameter before adding a return value type to the function itself.TypeScript can automatically infer the return value type from the return statement, so it can usually be omitted:

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

// Anonymous function
let myAdd = function(x: number, y: number): number {
    return x + y;
};

Complete function type

The complete function type consists of two parts: the parameter type and the return value type.

// (x: number, y: number) => number is the type of function
// x, y are just for readability, as long as the parameter types are matched, there is no need to match whether the parameter names are the same or not
// Use=>sign between parameter type and return value type
let myAdd: (x: number, y: number) => number = function(
    x: number,
    y: number
): number {
    return x + y;
};

The return value type is a necessary part of the function type, and if the function does not return a value, the return value must also be specified as void.

Inference Type

When a function is defined, the TypeScript compiler automatically recognizes the type if only one side of the assignment statement specifies the statement:

// myAdd has the full function type
let myAdd = function(x: number, y: number): number {
    return x + y;
};

// The parameters `x` and `y` have the type number
let myAdd: (baseValue: number, increment: number) => number = function(x, y) {
    return x + y;
};

This is called "categorizing by context", and is a type inference.

Optional and default parameters

By default, TypeScript will determine whether the parameters passed in to the function and the parameters defined by the function are consistent, and the number and type will be determined.

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

// An argument for 'increment' was not provided.
myAdd(1);
myAdd(1, 2);
// There should be two parameters, but three are obtained.
myAdd(1, 2, 3);

In TypeScript, optional parameters can be added, which must precede the required parameters:

function buildName(firstName: string, lastName?: string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        return firstName;
    }
}

// Bob
let result1 = buildName('Bob');
// There should be 1-2 parameters, but get 3.
let result2 = buildName('Bob', 'Adams', 'Sr.');
// Bob Adams
let result3 = buildName('Bob', 'Adams');

When defining a function, a parameter can be assigned a value as the default value, which is only used by the function when no value is passed or the value passed in is undefined:

function buildName(firstName: string, lastName = 'Smith') {
    return firstName + ' ' + lastName;
}

// Bob Smith
let result1 = buildName('Bob');
// Bob Smith
let result2 = buildName('Bob', undefined);

The default value of a function does not need to be placed after the required parameter, but the default value placed before the required parameter takes effect only when undefined is passed explicitly.

Remaining parameters

In JavaScript, all parameters passed in can be accessed using arguments; in TypeScript, they can also be used.

The remaining parameters treat a variable number of parameters as an array, representing 0 or more parameters:

// ... followed by an array, which is the remaining parameter
function buildName(firstName: string, ...restOfName: string[]) {
    return firstName + ' ' + restOfName.join(' ');
}

// Bob
console.log(buildName('Bob'));
// Bob Smith Steven
console.log(buildName('Bob', 'Smith', 'Steven'));

In other words, the remaining parameters must be final and cannot precede other parameters.

heavy load

Overloads allow a function to take different amounts or types of parameters and handle them differently.In JavaScript, overloading is typically achieved by determining the number or type of parameters passed in, and so on.

Overload the JavaScript version with the union type feature in TypeScript:

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

// function reverse(x: string | number): string | number
console.log(reverse(123));
console.log(reverse('123'));

The above is one way to achieve overload, but it is more difficult to understand and cannot be expressed accurately.TypeScript provides a more precise way to override:

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('')
        );
    }
    return x
        .split('')
        .reverse()
        .join('');
}

// function reverse(x: number): number (+1 overload)
console.log(reverse(123));
// function reverse(x: string): string (+1 overload)
console.log(reverse('123'));

Note that TypeScript prefers matching from the top function definitions, so multiple function definitions, if they have inclusion relationships, need to precede precise definitions.

Posted by suepahfly on Sun, 25 Aug 2019 19:27:18 -0700