Functions in TypeScript

Functions in TypeScript

1. Function definition

1.1 Functions in JavaScript

Before learning about functions in TypeScript, let's review the following commonly used function definitions in JavaScript:

The first method: Declare a function using the function keyword

function add1 (x, y) {
    return x + y
}


Second method: Declare functions using literal values

const add2 = function (x, y) {
    return x + y
}


The third method: using arrow functions to declare functions

const add3 = (x, y) => {
    return x + y
}


1.2 Functions in TypeScript

The function declaration method in TS is similar to that in JS. The only difference is that the parameter type and return value type are fixed. If there is no return value, the return value type must be void instead of leaving it blank.

Next, we use TS to re-declare the above three functions:

The first method is to use the function keyword to declare the function:

/*
 The syntax structure is as follows: function function name (parameter 1: type, parameter 2: type, ...): return value type {
     Function body}
 */
function add4(x: number, y: number): number {
    return x + y
}


Second method: Declare functions using literal values

/*
 The syntax structure is as follows: const function name = function (parameter 1: type, parameter 2: type,...): return value type {
     Function body}
 */
const add5 = function (x: number, y: number): number {
    return x + y
}


The third method: using arrow functions to declare functions

/*
 The syntax structure is as follows: const function name = (parameter 1: type, parameter 2: type,...): return value type => {
     Function body}
 */
// 3. Use arrow function to declare function const add6 = (x: number, y: number): number => {
    return x + y
}


The above is how to declare functions in TS. There is also a situation of parameter decoupling assignment in JS. How to specify the parameter type in TS? The sample code is as follows:

const add7 = ({ x, y }: { x: number; y: number }): number => {
    return x + y
}

There is also a more readable way of writing in TS, as shown below:

const add8: (baseValue: number, increment: number) => number = function (
    x: number,
    y: number
): number {
    return x + y
}

This method divides the function into two parts. The first part is the return value type of the function, and the second part is where the function is defined.

In fact, the first half is just to increase the readability of the code and does not have much practical significance.

2. Optional parameters and default parameters

Every function in TypeScript is required. This does not mean that null and undefined cannot be passed as parameters, but whether a value is passed for each parameter. If there is no one-to-one correspondence, an exception will be thrown. Simply put, the number of formal parameters is the same as the number of actual parameters.

The sample code is as follows:

function add(x: number, y: number): number {
    return x + y
}
let result1 = add(1) // Expected 2 arguments, but got 1.
let result2 = add(1, 2)
let result3 = add(1, 2, 3) // Expected 2 arguments, but got 3

In JS, each parameter is optional and can be passed or not. If it is not passed, it will be the default value of undefined .

This is also possible in TS. We only need to add ? after the parameter name to implement the optional parameter function.

The following code:

// Implement optional parameter function // Just add a ? next to the parameter name function add(x: number, y?: number): number {
  return x + y
}
let result1 = add(1)
let result2 = add(1, 2)
// let result3 = add(1, 2, 3) // Expected 2 arguments, but got 3

The above code implements optional parameters

Implementing default parameters in TS is the same as implementing default parameters in JS. You just need to assign values ​​to them.

The sample code is as follows:

;(function () {
  function add(x: number, y: number = 2): number {
    return x + y
  }
  let result1 = add(1) // 3
  let result2 = add(1, 2) // 3
})()

Of course, if you don't specify a type for y, it will be exactly the same as in JS.

3. Remaining parameters

The so-called remaining parameters are when two parameters need to be passed when the function is defined, but three parameters are passed when the function is called; at this time, there is an extra parameter, which is the remaining parameter.

In JS we can use arguments to access extra passed parameters. So how do you access the remaining parameters in TS?

In fact, in TS, all parameters can be stored in a variable, which is actually a decoupled array.

The sample code is as follows:

function fun(x: number, ...numbers: number[]): void {
    console.log(numbers)
}
fun(1, 2, 3, 4) // [ 2, 3, 4 ]

This is the end of this article about functions in TypeScript. For more relevant TypeScript function content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Function overloading in TypeScript
  • TypeScript function definition and use case tutorial
  • Explanation of TypeScript common types and application examples
  • Classes in TypeScript
  • Do you understand functions and classes in TypeScript?

<<:  Mysql case analysis of transaction isolation level

>>:  How to implement rounded corners with CSS3 using JS

Recommend

Example of how to deploy MySQL 8.0 using Docker

1. Refer to the official website to install docke...

Detailed explanation of the solution to the nginx panic problem

Regarding the nginx panic problem, we first need ...

Summary of the differences between global objects in nodejs and browsers

In Node.js, a .js file is a complete scope (modul...

Vue form input binding v-model

Table of contents 1.v-model 2. Binding properties...

Share the problem of Ubuntu 19 not being able to install docker source

According to major websites and personal habits, ...

Detailed explanation of Vue life cycle

Table of contents Why understand the life cycle W...

MySQL's method of dealing with duplicate data (preventing and deleting)

Some MySQL tables may contain duplicate records. ...

The difference between Input's size and maxlength attributes

I recently used the input size and maxlength attri...

Seven different color schemes for website design experience

The color matching in website construction is ver...

Why the explain command may modify MySQL data

If someone asked you whether running EXPLAIN on a...

vue3.0+echarts realizes three-dimensional column chart

Preface: Vue3.0 implements echarts three-dimensio...

How to set an alias for a custom path in Vue

How to configure custom path aliases in Vue In ou...