Function type constraint
This is essentially a type constraint on the input and output of a function.
-
Function declaration
Export {} // Function name (parameter 1: type, parameter 2: type): return value type of functionfun1(a:number,b:string):string{return’666′}
// fun1(2,’5′,66)
Optional parameter use? Mark, c? :number, can not pass the parameter, but if the parameter is passed, the corresponding type must be used:
Export {} // Function name (1: type, 2: type, optional 3? : type) : function return value type functionfun1(a:number,b:string,c? :number):string{ return'666' } fun1(2,'5',66)Copy the code
However, optional parameters (ES6 syntax) are marked with default values. Once the default values are set, the parameters become optional:
Function name (parameter 1: type, parameter 2: type, optional parameter 3? : type): return value type of functionfun1(a: number, b: string, c: number =6):string {return'666'} fun1(2,'5',66)Copy the code
If you want to accept any number of arguments, you can use the REST operator of ES6. Note that REST is an array:
functionfun1(a: number, b: string,... Rest: number[]): string {return'666'} fun1(2,'5',66,88,99)Copy the code
** Note: ** Either way, optional arguments must be placed at the end of the argument.
-
Functional expression
There is no difference in the way it is written:
const fun2 =function (a: object, b: string): object {
return {}
}
fun2({},'55')
Copy the code
However, because the function is being accepted as a variable, and a variable should have a type, TS will generally infer our type from the function expression. If used as a callback, we need to constrain the type passed in:
const fun2: (a: object, b: string) => object =function (a: object, b: string): object {
return {}
}
fun2({},'55')
Copy the code
This is often used when defining interfaces, which we’ll talk about later.
Any type
Because JS is weakly typed, it can accept arguments of any type. TS is JS compatible, so it is inevitable to encounter any type of situation when coding, such as:
Functionstr (value:any){// because json. stringify is capable of receiving // methods of any type, STR (6) STR ("xiling")Copy the code
Using any allows you to use any type, and you won’t get errors in the syntax. Note that there is no syntax error, because TS does not do type checking when using any, so using any is a huge type safety issue.
Using any, just like using traditional JS, results in a lot of overuse of any.
Implicit type inference
If a variable has no first type, type inference is automatically made based on the type of the value.
If the definition variable is not assigned, it is inferred to be of type any. However, it is strongly recommended that variables be declared with explicit type constraints.
To be continued…