function

function function_name() :return_type { 
    / / statements
    return value; 
}
Copy the code
  • Return_type is the type of the return value.
  • The return keyword is followed by the result to return.
  • In general, a function has only one return statement.
  • The type of the return value needs to be the same as the return type defined by the function (return_type)

Function types

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

// The arguments x and y are both of type number. Add the two arguments and convert them to string.
// So the whole function returns a string
const add = function(x: number, y: number) :string {
  return (x + y).toString()
}
// The arrow function is overwritten
const add = (x: number, y: number): string= > (x + y).toString()
Copy the code

The full type of the function

const add: (x: number, y: number) = > string = function(x: number, y: number) :string {
  return (x + y).toString()
}
// The arrow function is overwritten
// The position and type of the parameters remain unchanged. The variable name can be defined by itself, for example, the two parameters are positioned as a and b
const add: (a: number, b: number) = > string = (x: number, y: number): string= > (x + y).toString()
Copy the code

Parameters of a function

The number of parameters remains the same

Every function parameter is required in TypeScript. This does not mean that null or undefined cannot be passed as an argument, but rather that the compiler checks whether the user has passed in a value for each argument. In short, the number of arguments passed to a function must be the same as the number of arguments expected by the function.

const fullName = (firstName: string, lastName: string): string= > `${firstName}${lastName}`

let result1 = fullName('Sherlock'.'Holmes')
let result2 = fullName(null.undefined)
let result3 = fullName('Sherlock'.'Holmes'.'character') //Error--Expected 2 arguments, but got 3
let result4 = fullName('Sherlock') //Error--Expected 2 arguments, but got 1, An argument for 'lastName' was not provided.
Copy the code

Optional parameters

Each argument is optional in JavaScript, and can be passed or not. When no parameter is passed, its value is undefined.

In TypeScript we can use it next to parameter names, right? Realize the function of optional parameters, optional parameters must be followed by the required parameters, optional parameters are not allowed to appear after the required parameters.

constfullName = (firstName: string, lastName? : string):string= > `${firstName}${lastName}`

let result1 = fullName('Sherlock'.'Holmes')
let result2 = fullName('Sherlock'.'Holmes'.'character') // Error, Expected 1-2 arguments, but got 3
let result3 = fullName('Sherlock')                        // OK
Copy the code

The default parameters

Optional parameters must be placed after required parameters. Parameters with default values do not need to be placed after required parameters. They can be adjusted at will:

function buildName(firstName: string, lastName = "Smith") {
  return firstName + "" + lastName;
}
console.log(buildName("Bob"))  // Bob Smith
console.log(buildName("Bob".undefined))  //Bob Smith
console.log(buildName("Bob"."Adams"))  //Bob Adams
Copy the code

The remaining parameters

When the number of arguments to a function is indeterminate, an unknown number may be passed, and rest arguments (of the form… Variable name) to get the rest of the function arguments, so you don’t need to use the Arguments object.

Note that the REST parameter can only be the last parameter

// The second argument takes the rest of the arguments, all of which are strings
function assert(ok: boolean, ... args: string[]) :void { 
  if(! ok) {throw new Error(args.join(' ')); }}// The first argument is passed as a Boolean, followed by an infinite number of string arguments
assert(false.'Upload file is too large'.'JPG format only')
Copy the code

This parameter

In JavaScript, the value of this is only specified when a function is called, but it takes some time to figure out what this actually means.

Json by default, the noImplicitThis property on compilerOptions is false. When we use this in an object, it is of type any.

let triangle = {
  a: 10.b: 15.c: 20.area: function () {
    return () = > {
      // This is of type any
      const p = (this.a + this.b + this.c) / 2
      //const p = (this.d + this.d + this.d) / 2
      return Math.sqrt(p * (p - this.a) * (p - this.b) *(p - this.c))
    }
  }
}

const myArea = triangle.area()
console.log(myArea())
Copy the code

So we should specify what this refers to

  • First, in tsconfig.json, set the compilerOptions property noImplicitThis to true and the TypeScript compiler will do the correct type inference

  • Solve the problem that this is of type any by taking the form of this. Provide an explicit this argument, which appears at the top of the argument list:

interface Triangle {
  a: number;
  b: number;
  c: number;
  area(this: Triangle): () = > number;
}

let triangle: Triangle = {
  a: 10.b: 15.c: 20.area: function (this: Triangle) {
    return () = > {
      const p = (this.a + this.b + this.c) / 2 / / this point to the Triangle
      return Math.sqrt(p * (p - this.a) * (p - this.b) *(p - this.c))
    }
  }
}

const myArea = triangle.area()
console.log(myArea())
Copy the code

Function overloading

Function overloading refers to a function that returns different types of data depending on the parameters passed in.

Character inversion problem (not considering negative cases) :

function reverse(target: string | number) {
  if (typeof target === 'string') {
    return target.split(' ').reverse().join(' ')}if (typeof target === 'number') {
    return +[...target.toString()].reverse().join(' ')}}console.log(reverse('imooc'))   // coomi
console.log(reverse(23874800))  / / 847832
Copy the code

The compiler does not know what type the input parameter is, nor is the return value type. It is possible to provide multiple function type definitions for the same function for function overloading.

(Added support for generator and iterator protocols with the –downlevelIteration build option)

function reverse(x: string) :string
function reverse(x: number) :number

function reverse(target: string | number) {
  if (typeof target === 'string') {
    return target.split(' ').reverse().join(' ')}if (typeof target === 'number') {
    return +[...target.toString()].reverse().join(' ')}}console.log(reverse('imooc'))   // coomi
console.log(reverse(23874800))  / / 847832
Copy the code

Because this inversion function returns a string type when it is passed in and a number when it is passed in, the function type definition is done twice in the first two lines. During function execution, different calculations are performed depending on the type of argument passed in.

To enable the compiler to select the correct check type, it matches from the first in the overload list. Therefore, when defining overloads, it is important to put the most precise definition first.

Considerations when using functions

  1. If a function is not usedreturnStatement, it returns by defaultundefined.
  2. The value passed to a function when it is called is called of the functionThe arguments(value passing), the function argument at the corresponding position is calledparameter.
  3. While the function is executing,thisThe keyword does not refer to the running function itself, but ratherRefers to the object calling the function.
  4. argumentsThe object is available in all (non-arrow) functionsA local variable. You can use arguments objects to refer to function arguments in functions.

Learning links

  • www.tslang.cn/docs/handbo…
  • www.imooc.com/wiki/typesc…