This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging

1. Function declaration

Function student(x:string,y:number):string{return '${y}'} console.log(x:string,y:number):string{return '${y}} console.log(x:string,y:number))Copy the code

Let’s see what’s different from javascript

  • The type of the argument is specified (to be followed because of type checking), and the return value type of the function is determined
  • The parameters can’t be too many or too few, just right, and it depends on the order.

Function expression

Let student:(x:string,y:number)=>string = function(name:string,age:number):string{return '${name}'}Copy the code
  • Parameter names may be different
  • Use void if the function does not return a value

This parameter is optional

Function student(y:number,x:string=' y '):string{return '${y}} console.log(y:number,x:string)Copy the code
  • As you can see, the parameters of the default value are identified as optional, but not necessarily after the required parameters.
  • Although it is optional, it does not need to be placed after the required argument, but once it is placed before the required argument, it must explicitly write undefined or a value, so it cannot be empty.

Optional parameters

Function student(y:number,x:string); :string):string{return '${y}} console.log(student(9,undefined)) :string{return' ${y}} console.log(student(9,undefined))Copy the code
  • Optional arguments should be placed after required arguments

The remaining parameters

function student(y:number,x:string,... name:string[]):void{ console.log(... Name)} the console. The log (student (1, 'pig small fart', 'pig small beauty', 'big orange tiger'))Copy the code
  • The remaining arguments are treated as an unlimited number of optional arguments, either none or any. Again, after the necessary parameters.
  • Is an array type whose name is the field name following the ellipsis. You can use this array in the body of the function.

** Function overloading **

  • Method overloading in Java: Function overloading occurs when two or more functions with the same name take different arguments
  • Overloading in ts: Serves the purpose of multiple functions by providing multiple function type definitions for the same function.
  • Ts in order to be compatible with ES5 ES6 overload writing and Java in a different way.
function getUserInfo(name:string):string; function getUserInfo(name:number):number; Function getUserInfo(name:any):any{if (typeof name === 'string') {return 'my name '+ name; }else{ return name; }} console.log(getUserInfo(' pig ')); Console. log(getUserInfo(5)); //=> my age is 5 //console.log(getUserInfo(true)); // Error writingCopy the code