Home >Web Front-end >JS Tutorial >Detailed introduction to functions in typescript
This article brings you a detailed introduction to the functions in typescript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Needless to say the role of functions, let’s take a look at the true appearance of functions in the typescript world!
The basic appearance of the function is as follows:
function fnanme(arg1: Type1, arg2: Type2, ...):Type { // 函数体 }
Function name parameters function body return value
The function name is of course a legal identifier, there is nothing to say, the important thing is the parameters and return value determine the shape of this function.
As for the function body, it is the code that implements the function, which varies depending on the function.
Parameter declaration
The parameter is the input of the function and needs to conform to a specific type of format
The parameters in the function declaration are called formal parameters, and when called What the function passes is called the actual parameter
The format of each parameter is name: Type, the front represents the parameter name, and the back represents the parameter type; multiple parameters need to be separated by commas, which is also very common. The following is an example
function fa(name: string, age: number) {}
Optional parameters
Parameters do not have to be passed, you can pass them if you want to, if you don’t want to not pass them, add one after the parameter name ?, this function can be achieved
For example,
function fa(name: string, age?: number) {}
means that age can be passed or not.
Default parameters
By giving the parameter A default value can actually achieve the effect of optional parameters, but the effect achieved at this time is that when this parameter is not passed, the default parameter will be used instead
It is worth noting that optional parameters must be required. After selecting the parameters, otherwise the compiler will be confused. In fact, think about it, if you don't do this, you will be confused too.
Function return
The function return must have a return type. The return type is usually written in front of the function body, that is, in front of the curly braces.
function fa(name: string): string {}
The return type of the above function is the string type. Of course, you can use any type you want.
When you do not declare a return type, the compiler will automatically infer your return type based on the return in your function body. If there is no return, the return type will be void
The above is the detailed content of Detailed introduction to functions in typescript. For more information, please follow other related articles on the PHP Chinese website!