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

Summary of three rules for React state management

Table of contents Preface No.1 A focus No.2 Extra...

Detailed examples of Zabbix remote command execution

Table of contents one. environment two. Precautio...

Summary of some efficient magic operators in JS

JavaScript now releases a new version every year,...

SQL Aggregation, Grouping, and Sorting

Table of contents 1. Aggregate Query 1. COUNT fun...

How to deploy HTTPS for free on Tencent Cloud

Recently, when I was writing a WeChat applet, the...

How to install Django in a virtual environment under Ubuntu

Perform the following operations in the Ubuntu co...

mysql calculation function details

Table of contents 2. Field concatenation 2. Give ...

MySQL database migration quickly exports and imports large amounts of data

Database migration is a problem we often encounte...

DIV common attributes collection

1. Property List Copy code The code is as follows:...

Execution context and execution stack example explanation in JavaScript

JavaScript - Principles Series In daily developme...

Simple implementation of html hiding scroll bar

1. HTML tags with attributes XML/HTML CodeCopy co...

JavaScript code to implement a simple calculator

This article example shares the specific code of ...

mysql-8.0.17-winx64 deployment method

1. Download mysql-8.0.17-winx64 from the official...

How to write CSS elegantly with react

Table of contents 1. Inline styles 2. Use import ...

Some front-end basics (html, css) encountered in practice

1. The div css mouse hand shape is cursor:pointer;...