TypeScript の 7 starting from 0: function

Posted by gigantorTRON on Wed, 22 Dec 2021 03:13:38 +0100

introduce

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

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

TypeScript adds additional functionality to JavaScript functions to make it easier to use.

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

However, as long as you have some basic JavaScript, you should not find it difficult to learn the function knowledge in TypeScript


Function definition

JavaScript function definition

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

  • Function Declaration
  • Function Expression
// Function declaration
function abc() {  }

// Function expressions assign anonymous functions to variables
let def = function() {  }

TypeScript function definition

These two methods can also be used to define functions in typescript, but constraints are required. As mentioned in the previous blog, type definition is the simplest function constraint.

// Function has input and output. In TS, if there is a constraint, you need to use type definition
// The parameter and return value of addNum must be of type number
function addNum( a: number, b: number ): number {
    return a + b;
}

If the defined function has no return value, you can use void null value. This function type before https://juejin.cn/post/6992001689867780126 Also mentioned in.

In the following example, if you write the return value return a;, The error Type 'number' is not assignable to type 'void' will occur

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

Note: unlike JavaScript, addNum cannot enter extra (or less than the required) parameters after using constraints. If "is used to make an optional declaration of parameters, it may not be entered when calling parameters

TypeScript full function

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

In TypeScript, there is = >. However, this is a different definition from the arrow function = > in es6.

In the type definition of TypeScript, = > is used to represent the function definition. On the left is the input type, which needs to be enclosed in parentheses, and on the right is the output type.

example:

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

Of course, if you don't define the return type for the function, you can succeed. This is because there are inference types in ts, and "categorizing by context" is a kind of type inference. It helps us better specify types for programs.

Optional parameters

The optional parameters of the function are added after the parameters when the method is defined?, Optional parameters should be placed at the end, and mandatory parameters and default parameters should be placed in front of them

example:

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

Default parameters

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

When using default parameters, optional parameters are placed last.

function sort( a: number, b: number = 30 ): boolean {
    return a > b;
}
sort(5);    // If the default parameter is not transferred, the default value will be taken, that is, 5 and 30 will be compared
sort(5, 3);   // When the default parameter is passed, the default value will be overwritten, that is, the comparison between 5 and 3

Remaining parameters

Sometimes you want to manipulate multiple parameters at the same time, or you don't know how many parameters will be passed in. In JavaScript, you can use arguments to access all the parameters passed in.

In typescript, all parameters can be collected into one variable. There is a name in es6 This operator is mainly used to call when a function operates

Define here When extending operators, the type can be set to array

The following is an example of an accumulation method:

let add = (...arr: number[]):number => {
    let all:number = 0;
    arr.map((item)=>{
        all += item as number;
    })
    return all;
}
console.log(add(1, 2, 3));  // 6

function overloading

Overloading in typescript: multiple functions are achieved 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.

In JavaScript, if the same method name is encountered, the above method will be overwritten with the following method without error. However, in typescript, this definition method will make mistakes. The cause of the error is a duplicate implementation of the function

TS overload implementation:

function css( config:string ):string;

function css( config:string, value:number ):string;
// Reload 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));

In fact, I personally feel that the overload of typescript is uncomfortable to write, so try to reduce the method of repeated naming

Topics: Javascript Front-end TypeScript