• Chinese version of TypeScript Tutorial – Project introduction
  • TypeScript Tutorial Chinese version – Section 0. preface
  • TypeScript Tutorial Chinese version – Section 1. An introduction to
  • TypeScript Tutorial Chinese version – Section 2. Basic types of
  • TypeScript Tutorial Chinese version – Section 3. Control flow statement
  • TypeScript Tutorial Chinese – Section 4. function
  • TypeScript Tutorial Chinese version – Section 5. class
  • TypeScript Tutorial Chinese version – Section 6. interface
  • TypeScript Tutorial Chinese version – Section 7. High-level types
  • TypeScript Tutorial Chinese version – Section 8. The generic
  • TypeScript Tutorial Chinese version – Section 9. The module
  • Chinese version of TypeScript Tutorial – Section 10.node.js

Section 4. The function

function

The original address

In this tutorial, you’ll learn about functions in TypeScript and how to add type comments to functions.

An introduction to TypeScript functions

A function in TypeScript is a readable, maintainable, and reusable block of code. Like JavaScript, you can declare functions in TypeScript using the function keyword:

function name(parameter: type, parameter: type.) :returnType {
  // do something
}
Copy the code

Unlike JavaScript, TypeScript allows you to add type comments to function arguments and return values. Look at the add() function below:

function add(a: number, b: number) :number {
  return a + b;
}
Copy the code

In this example, the add() function takes two numeric parameters. When you call add(), the TypeScript compiler checks each argument passed to the function to make sure it is a numeric value. In the add() example, you can only pass numeric parameters to it, not values of any other type. The following example throws an error because it passes two string arguments to the add() function:

let sum = add('10'.'20');
Copy the code

Error message:

error TS2345: Argument of type '" 10 "' is not assignable to parameter of type 'number'
Copy the code

The: number after the parentheses indicates the type of return value, in this case the add() function returns a value of type number. When a function has a return type, the TypeScript compiler checks each return statement against the return type to ensure that the return value is compatible. If the function does not return a value, use void as the return type. The void keyword means that the function does not return any value, as follows:

function echo(message: string) :void {
  console.log(message.toUpperCase());
}
Copy the code

The void type prevents the code inside a function from returning a value, and prevents the function’s return from being assigned to the variable where the function was called.

When there is no comment return value type, TypeScript tries to infer its type as follows:

function add(a: number, b: number) {
  return a + b;
}
Copy the code

In this example, the TypeScript compiler tries to infer the type of the return value of the add() function as number, which is expected. However, if multiple branches of a function return different types of values, the TypeScript compiler may infer that the return value is of the union type or any type. Therefore, add type comments to functions whenever possible.

summary

  • Add type comments to the arguments and return values of a function to ensure that the calling code is inlined and that type checking is performed in the function body.

Function types

The original address

In this tutorial, you’ll learn about TypeScript function types and use them to define types for functions.

An introduction to TypeScript function types

A function type consists of two parts: a parameter type and a return type. When declaring a function type, use the following syntax to specify both parts:

(parameter: type.parameter: type,...). = >type
Copy the code

The following example declares a function type that takes two numeric types and returns a value of numeric type:

let add: (x: number, y: number) = > number;
Copy the code

In this example:

  • The function type takes two arguments:xyBoth of themnumberType value;
  • The return value is of typeNumeric types, followed by the fat arrow between the argument list and the return type= >Behind).

Note that the parameter names (x and y) are just easy to read; you can use other parameter names.

When you add a function type comment to a variable, you can assign a function of the same type to the variable. The TypeScript compiler checks whether the number and types of arguments and return types match. The following example shows how to assign a function to the add variable:

add = function (x: number, y: number) {
  return x + y;
};
Copy the code

Similarly, we can declare a variable and assign a function to it as follows:

let add: (a: number, b: number) = > number = function (x: number, y: number) {
  return x + y;
};
Copy the code

If you assign another function whose type does not match the type of the add function, TypeScript throws an error as shown in the following:

add = function (x: string, y: string) :number {
  return x.concat(y).length;
};
Copy the code

Function type inference

When there is a type on one side of the equation, the TypeScript compiler can infer the type of a function. This form of type inference is called context type, as follows:

In this example, the add function is inferred to be of type (x: number, y:number) => number.

By type inference, you can eliminate some of the type annotation work and significantly reduce the amount of code.

Optional parameters

The original address

In this tutorial, you’ll learn how to use optional arguments to TypeScript functions.

In JavaScript, even if a function has specified parameters, it can be called without passing any parameters, because JavaScript supports optional parameters by default. In TypeScript, the compiler checks each function call and throws an error if:

  • The number of arguments is different from the number of parameters specified in the function;
  • Or the type of the argument is incompatible with the type of the function parameter.

Since the compiler thoroughly checks the arguments passed to the function, we can use optional arguments to tell the compiler that the arguments are optional, without raising an error if they don’t exist.

To make function arguments optional, add? To the parameter name. Symbol, as follows:

function multiply(a: number, b: number, c? :number) :number {
  if (typeofc ! = ='undefined') {
    return a * b * c;
  }
  return a * b;
}
Copy the code

Here’s how it works:

  • First, incAdd after parameter?Symbols;
  • And then, by expressiontypeof c ! == 'undefined'checkcWhether arguments are passed to the function.

Note: If you use the expression if(c) to check whether the argument is initialized, you will find that the empty string and 0 are also treated as undefined, which is problematic.

Optional parameters must appear after mandatory parameters in the parameter list. For example, if you make b optional and C mandatory, the TypeScript compiler throws an error:

function multiply(a: number, b? :number, c: number) :number {
  if (typeofc ! = ='undefined') {
    return a * b * c;
  }
  return a * b;
}
Copy the code

Error message:

error TS1016: A required parameter cannot follow an optional parameter.
Copy the code

summary

  • useparameter? : typeSyntax sets parameters to optional;
  • usetypeof(parameter) ! == 'undefined'Expression to check whether optional arguments are initialized.

The default parameters

The original address

In this tutorial, you’ll learn about default arguments in TypeScript

An introduction to default arguments in TypeScript

JavaScript has supported default parameters since ES2015 (or ES6). The syntax is as follows:

function name(parameter1 = defaultValue1, ...) {
  // do something
}
Copy the code

In the above syntax, if a function is called with no argument or with undefined, the function assigns the default initial value to the default parameter, as follows:

function applyDiscount(price, discount = 0.05) {
  return price * (1 - discount);
}

console.log(applyDiscount(100)); / / 95
Copy the code

In this example, the applyDiscount() function has a default argument discount. If the applyDiscount() function does not pass a value to the discount line argument when it is called, the default value of 0.05 is assigned to it. Like JavaScript, you can use the same syntax in TypeScript to specify default parameters:


function name(parameter1 :type = defaultvalue1, parameter2 :type = defaultvalue2, ...) {
  //
}
Copy the code

The following example uses the default argument to the applyDiscount() function:

function applyDiscount(price: number, discount: number = 0.05) :number {
  return price * (1 - discount);
}

console.log(applyDiscount(100)); / / 95
Copy the code

Note that you cannot include default arguments in the function type definition. The following code will raise an error:

let promotion: (price: number, discount: number = 0.05) = > number;
Copy the code

Error message:

error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
Copy the code

Default and optional parameters

Like optional parameters, default parameters are optional. This means that you can omit default arguments when calling a function. In addition, default arguments and optional arguments may have the same type, such as the following two functions:

function applyDiscount(price: number, discount: number = 0.05) :number {
  // ...
}
Copy the code

and

function applyDiscount(price: number, discount? :number) :number {
  // ...
}
Copy the code

They have the same type as shown below:

(price: number, discount? :number) = >number;
Copy the code

The optional parameter must come after the mandatory parameter, but the default parameter does not need to come after the mandatory parameter. When a default parameter appears before a mandatory parameter, you need to explicitly pass undefined to get an assignment of the default initial value.

The following function returns days in the specified month and year:

function getDay(
  year: number = new Date().getFullYear(),
  month: number.) :number {
  let day = 0;
  switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      day = 31;
      break;
    case 4:
    case 6:
    case 9:
    case 11:
      day = 30;
      break;
    case 2:
      // leap year
      if ((year % 4= =0 && !(year % 100= =0)) || year % 400= =0) day = 29;
      else day = 28;
      break;
    default:
      throw Error('Invalid month');
  }
  return day;
}
Copy the code

In this case, year defaults to the current year if no argument or undefined is passed to it. The following example uses the getDay() function to get the number of days in February 2019:

let day = getDay(2019.2);
console.log(day); / / 28
Copy the code

To get the number of days in February of this year, we need to pass undefined to year as follows:

let day = getDay(undefined.2);
console.log(day);
Copy the code

summary

  • If you want to set the default initial value of the parameter, use the syntax of the default parameterparameter:=defaultValue;
  • Default parameters are optional;
  • To use the default initial value of the parameter, ignore the argument or call the functionundefinedThe value is passed to the corresponding parameter.

Rest parameters

The original address

In this tutorial, you’ll learn about TypeScript’s residual parameters, which allow you to represent an unlimited number of parameters as an array of parameters.

Rest parameters allow functions to accept zero or more arguments of the specified type. In TypeScript, Rest parameters follow the following rules:

  • A function has only one Rest argument;
  • Rest arguments appear at the bottom of the argument list;
  • The Rest parameter is of type array.

To declare a Rest parameter, precede the parameter name with three dots and annotate it with an array type:

function fn(. rest:type[]) {
  / /...
}
Copy the code

The following example demonstrates how to use Rest parameters:

function getTotal(. numbers:number[]) :number {
  let total = 0;
  numbers.forEach((num) = > (total += num));
  return total;
}
Copy the code

In this example, the getTotal() function calculates the sum of all the arguments passed to it. Since the numbers argument is a Rest argument, you can pass one or more numbers to calculate their sum:

console.log(getTotal()); / / 0
console.log(getTotal(10.20)); / / 30
console.log(getTotal(10.20.30)); / / 60
Copy the code

Function overloading

The original address

In this tutorial, you’ll learn about function overloading in TypeScript

An introduction to function overloading in TypeScript

In TypeScript, function overloading allows you to establish a relationship between a function’s parameter type and its return type.

Note that TypeScript’s function overloading differs from that supported by other statically typed languages such as C# and Java.

Let’s look at a few simple examples:

function addNumbers(a: number, b: number) :number {
  return a + b;
}

function addStrings(a: string, b: string) :string {
  return a + b;
}
Copy the code

In this example:

  • addNumbers()Function returns the sum of two numbers;
  • addStrings()The concatenate () function returns the result of concatenating two strings.

You can use union types to define the type range of a function argument and return value:

function add(a: number | string, b: number | string) :number | string {
  if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
  }

  if (typeof a === 'string' && typeof b === 'string') {
    returna + b; }}Copy the code

However, the union type cannot accurately represent the relationship between the parameter type and the return value type. The add() function tells the compiler that it will take a number or string argument and returns a number or string. But it does not describe returning numbers when all arguments are numbers and strings when all arguments are strings. To better describe the relationships between the types used by functions, TypeScript supports function overloading, as follows:

function add(a: number, b: number) :number;
function add(a: string, b: string) :string;
function add(a: any, b: any) :any {
  return a + b;
}
Copy the code

In this example, we add two function overloads to the add() function. The first overload tells the compiler that add() should return a number when all arguments are numbers. The second function overload has similar behavior, but with arguments to the string type.

Each function overload defines the combination of types supported by the add() function, describing the mapping between parameter types and the types of its return values. Now when you call add(), the code editor prompts you for an overloaded function that is available, as follows:

Optional arguments are used in number function overloading

When you use function overloading, the functions must have the same number of arguments. If one function overloads more arguments than another, you must set the extra arguments to optional, as shown below:

function sum(a: number, b: number) :number;
function sum(a: number, b: number, c: number) :number;
function sum(a: number, b: number, c? :number) :number {
  if (c) return a + b + c;
  return a + b;
}
Copy the code

The sum() function takes two or three arguments of type number. The third argument is optional, and the compiler will throw an error if it is not made optional.

Method overloading

When a function is a property of a class, it is called a method, and TypeScript also supports method overloading, as shown below:

class Counter {
  private current: number = 0;
  count(): number;
  count(target: number) :number[]; count(target? :number) :number | number[] {
    if (target) {
      let values = [];
      for (let start = this.current; start <= target; start++) {
        values.push(start);
      }
      this.current = target;
      return values;
    }
    return ++this.current; }}Copy the code

The count() function can return either a number or an array, depending on the number of arguments passed to it.

let counter = new Counter();

console.log(counter.count()); // return a number
console.log(counter.count(20)); // return an array
Copy the code

Output:

1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]Copy the code

summary

  • Function overloading in TypeScript allows you to describe the relationship between function parameter types and return types.