Function, first-class citizen.
Function Declaration
// function.ts
function sum(x: number, y: number) :number {
return x + y;
}
Copy the code
With the understanding of the interface definition, a function with one more argument and one less argument (without optional operation on the argument) should not work either. Have a try
// function2.ts
function sum2(x: number, y: number) :number {
return x + y;
}
sum2(1.2);
sum2(1.2.3);
sum2(1);
// function2.ts:7:12 - Error TS2554: Expected 2 arguments, but got 3
// 7 sum2(1, 2, 3);
// 0.0.6/function2.ts:9:1 - Error TS2554: Expected 2 arguments, but got 1
// 9 sum2(1);
/ / 0.0.6 function2. Ts: gad
// 1 function sum2(x: number, y: number): number {
// An argument for 'y' was not provided.
Copy the code
The hint is obvious, it means we have one more parameter, one less parameter. In summary, the number of arguments in a function is immutable.
Function expression
// function3.ts
const sum3 = function(x: number, y: number) :number {
return x + y;
}
Copy the code
= (→_→) = (→_→) = (→_→) How do you define that?
// function4.ts
const sum4: (x: number, y: number) = > number = function(x: number, y: number) :number {
return x + y;
}
Copy the code
(x: number, y: number) => number (x: number, y: number) => number In Typescript, => defines functions with input types (enclosed by () on the left and output types on the right. In fact, the extra content can not be added manually, because the type can be inferred by the assignment operation.
Move 3: Interfaces
// function5.ts
interface Function5 {
(x: string, y: string) :boolean
}
let function5: Function5 = (x: string, y: string) = >{
return x.search(y) > - 1;
}
Copy the code
The above example uses the interface form to support the arrow function of ES6.
Optional parameters
This works in the same way as interface types in the previous article
// function6.ts
const showMyName = (firstName: string, lastName? :string) :string= > {
if(lastName) {
return `${firstName}${lastName}`;
} else {
returnfirstName; }}console.log(showMyName('pr'));
console.log(showMyName('quack'.'goodbye'));
Copy the code
The compiled
// function6.js
var showMyName = function (firstName, lastName) {
if (lastName) {
return "" + firstName + lastName;
}
else {
returnfirstName; }};console.log(showMyName('pr'));
console.log(showMyName('quack'.'goodbye'));
Copy the code
Q: Can optional parameters be followed by parameters (mandatory)?
// function7.ts
constshowMyName7 = (firstName? :string, lastName: string) :string= > {
if(firstName) {
return `${firstName}${lastName}`;
} else {
returnlastName; }}// 0.0.6/function7.ts: 1:42-error TS1016: A required parameter cannot follow an optional parameter
// 1 const showMyName7 = (firstName? : string, lastName: string): string => {
Copy the code
The error occurs because optional parameters cannot be followed by parameters (mandatory).
The remaining parameters
We know that ES6 has rest parameters (of the form… Rest), to get extra arguments to a function so you don’t need to use arguments objects. What about REST in Typescript?
// function8.ts
// function8.ts
const push = (array: any[], ...rest: any[]) = > {
rest.forEach(r= > {
array.push(r);
});
}
let arr = [false];
push(arr, '1'.2.3);
const push1 = (array: any[], ...rest: any[], x: number) = > {
rest.forEach(r= > {
array.push(r);
});
rest.push(x);
}
// 0.0.6/function8.ts:11:30 - error TS1014: A rest parameter must be last in a parameter list.
// 11 const push1 = (array: any[], ... rest: any[], x: number) => {
Copy the code
Parameters array and.. Rest we all define types… Rest is just an array. In addition, neither remaining nor optional parameters can be followed by any parameters.
The default value
ES6 has operations that add default values to function arguments. What about Typescript? Can the parameters that set the default values have additional parameters?
// function9.ts
const showMyNameAgain = (firstName: string = 'pr', lastName? :string. rest:any[]) :string= > {
let tmp: string = ' ';
if(rest.length) {
tmp = rest.join(' ');
}
if(lastName) {
return `${firstName}${lastName}${tmp}`;
} else {
return `${firstName}${tmp}`; }}console.log(showMyNameAgain());
console.log(showMyNameAgain('fat rui'.'male'.'this year'.30));
Copy the code
The compiled
// function9.js
var showMyNameAgain = function (firstName, lastName) {
if (firstName === void 0) { firstName = 'pr'; }
var rest = [];
for (var _i = 2; _i < arguments.length; _i++) {
rest[_i - 2] = arguments[_i];
}
var tmp = ' ';
if (rest.length) {
tmp = rest.join(' ');
}
if (lastName) {
return "" + firstName + lastName + tmp;
}
else {
return ""+ firstName + tmp; }};console.log(showMyNameAgain()); // pr
console.log(showMyNameAgain('fat rui'.'male'.'this year'.30)); // Fat Rui, male 30 years old
Copy the code
As you can see from the above example, the default value is the same as the ES6 assignment. Also, we find that the remaining parameters can be placed after the optional parameters.
overloading
Reloading doesn’t mean reloading, so it’s not a literal meaning here. The actual meaning is to do different processing depending on the number or type of parameters.
For example, here is a scenario where a number is passed in and multiplied by 10 and returned, and a string is passed in and preceded by Hello and returned.
So let’s analyze the points
- The output value type must be the same as the input parameter type (union type is used).
- Do different operations according to the parameter type (use type judgment);
// function10.ts
const chongzai = (x: number | string) :number | string= > {
if(typeof x === 'string') {
return `hello, ${x}`;
} else if (typeof x === 'number') {
return x * 10; }}Copy the code
Return x * 10; return x * 10; return x * 10; Change to x * 10 + “; No error, but it doesn’t meet our requirements. So you have to type the function manually
// function11.ts
function chongzai2(x: string) :string;
function chongzai2(x: number) :number;
function chongzai2(x: number | string) :number | string {
if(typeof x === 'string') {
return `hello, ${x}`;
} else if (typeof x === 'number') {
return x * 10; }}Copy the code
Function chongzai2 was declared three times. The first two are function definitions, and the third is function implementation.
This code Github
You can…
Typescript array types
Next: Typescript built-in objects
Contents: A primer to Typescript’s short book