This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
Examples of TypeScript
This article delves into TypeScript functions.Copy the code
The TypeScript function
function hello () {}
const hello = function() {}
const hell0 = () = > {}
Copy the code
TypeScript defines functions exactly like normal JavaScript. So what’s interesting about function type annotations? First we define a function and annotate the type as described in the previous article.
function total( x: number, y: number ) :number {
return x + y
}
Copy the code
Above we typed the total function’s input parameter (that is, its parameter) and its return value. The return value of the total function can be inferred by type inference. So the above function can be abbreviated as:
function total( x: number, y: number ) {
return x + y
}
Copy the code
Although some function return values can be inferred, it is better to manually annotate all function return values in the actual project development process to enhance the robustness of the code and avoid some code writing errors inside the function.
Common function return value types
In addition to the number, string and other basic types mentioned above, there are also void, never and other special types.
// 例1
function dance() :void {
console.log('dancing');
}
Copy the code
As above: void is a common function return value type, representing null. This means that the current function does not need a return value. Type ‘XXX’ is not assignable to Type ‘void’.
// 例2
function errorEmitter () :never {
while(true) {}
// This code will never execute
}
Copy the code
As above: never is also a function return value type, indicating that the current function never completes. For example, an infinite loop or an exception is thrown.
Function arguments as objects (destruct)
function total({x, y}: {x: number, y: number}) :number {
return x + y
}
total({x: 1.y: 2}) // The value passed is an object
Copy the code
Do not write function total({x: number, y: number}) {}, especially if there is only one argument.
Finish this! If this article helps you at all, please give it a thumbs up.