This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

function

introduce

Functions are the foundation of JavaScript applications. It helps you implement abstraction layers, mock classes, information hiding and modules, and is a first-class citizen in JavaScript.

In TypeScript, although classes, namespaces, and modules are already supported, functions are still the primary place to define behavior.

TypeScript adds additional functionality to JavaScript functions, making them easier to use.

In TypeScript, functions are also divided into named functions and anonymous functions.

However, as long as you have some JavaScript basics, you shouldn’t find it difficult to learn TypeScript functions



The function definitions

JavaScript function definitions

In JavaScript, function definitions are divided into function declarations and function expressions:

  • Function Declaration
  • Function Expression
// Declare the function
function abc() {}// A function expression assigns an anonymous function to a variable
let def = function() {}Copy the code

TypeScript function definitions

You can also define functions in typescript in both ways, but you need to constrain them. In a previous blog post, we talked about type definitions. Using type definitions is the easiest way to constrain functions.

// The function has input and output. If TS is a constraint, you need to use type definition
// Make addNum's argument and return value must be of type number
function addNum( a: number, b: number ) :number {
    return a + b;
}
Copy the code

If you define a function that has no return value, you can use the void null value. This is the previous function type juejin.cn/post/699200…

In the following example, if you now write the return value return a; Type ‘number’ is not assignable to Type ‘void’.

let say = function(a: number) :void {}Copy the code

Note: Unlike JavaScript, addNum cannot enter more (or fewer) parameters when using constraints. If used? An optional declaration for a parameter that is not entered when the parameter is passed

TypeScript complete functions

A function type consists of two parts: the parameter type and the return value type. Both parts are required when writing out the full function type. Capture variables used in functions are not reflected in the type. In fact, these variables are hidden states of functions and are not part of the component API.

In TypeScript, => also exists. However, this is a different definition than the arrow function => in ES6.

In TypeScript type definitions, => is used to represent the definition of a function, with the input type on the left enclosed in parentheses and the output type on the right.

Example:

let fun2:() = > number = function() :number {
    return 10;
}
Copy the code

Of course, if you do not define a return type for the function, you can actually succeed. This is because there are inference types in TS, categorized by context, which is a kind of type inference. It helps us better specify types for programs.

Optional parameters

The optional arguments to a function are the ones that are added after the arguments when the method is defined. , optional parameters should be placed at the end, and mandatory parameters and default parameters should be placed at the beginning

Example:

function add(a? : number, b? : number) :void {}Copy the code

The default parameters

There is no way to set default parameters in JavaScript, but you can in typescript

When using the default parameters, put the optional parameters last.

function sort( a: number, b: number = 30 ) :boolean {
    return a > b;
}
sort(5);    // If the default parameter is not passed, it will take the default value, which is 5 compared to 30
sort(5.3);   // The default parameter is passed, which overrides the default value, which is 5 compared to 3
Copy the code

The remaining parameters

Sometimes you want to manipulate more than one parameter at a time, or you don’t know how many parameters will be passed in. In JavaScript, you can use arguments to access all arguments passed in.

In typescript, you can collect all parameters into a single variable. There’s one in ES6 called… This operator is called primarily for function operations

Here we define… When extending the operator, the type can be set to an array

Here is an example of an accumulation method:

letadd = (... arr: number[]):number= > {
    let all:number = 0;
    arr.map((item) = >{
        all += item as number;
    })
    return all;
}
console.log(add(1.2.3));  / / 6
Copy the code

Function overloading

Overloading in typescript: Serves multiple functions by providing multiple function type definitions for the same function

Example:

function css( config:string ) :void{}// error: Duplicate function implementation.

function css( config:string, value:number ) :void {}// error: Duplicate function implementation.
Copy the code

In JavaScript, if you encounter the same method name, the following method will override the above method without error. In typescript, however, this is an error. The error is caused by repeated implementation of the function

TS reload implementation:

function css( config:string ) :string;

function css( config:string, value:number ) :string;
// Overloads the above two CSS
function css(. str:any[]) :any { 
    if (str.length == 1) {
        return `${str[0]}`
    } else {
        return `${str[0]} + ${str[1]}`}}console.log(css('4'.5));
Copy the code

Personally, I find typescript overloading uncomfortable to write, so try to minimize the number of duplicate named methods