Learning TypeScript–Functions–Part 2Dec 9th, 2012 | By sankarsan | Category: Programming & Languages
TypeScript provides us the static type checking capability.So the function parameters & return types can have datatypes as shown below:
There is a specific datatype in TypeScript i.e. void which can be applied only for function return types.
TypeScript also support function to have optional parameters. The optional parameters are followed by a question mark(?) as shown below.
Also, we can avoid this “if” block by providing an initializer to the optional parameter as shown below:
Also, the default values of optional parameters can use other mandatory parameters as shown below. Here default value of “z” is same as whatever is passed for parameter “y”.
The trick is again done by the TypeScript compiler in similar way:
There is one rule which the compiler strictly enforces, that is an optional parameter must be followed only by optional parameters and not mandatory ones are not allowed.So the following code will not compile.
Compilation will fail with the following message: “Optional parameters may only be followed by other optional parameters”.
TypeScript also supports method overloading but in a bit cumbersome way (at least it seems cumbersome to me).We need to first write the method declarations for each of the overloads then we need to provide a generic implementation which supports all the signatures as shown below:
With this we have covered most of the important features related to functions. In the next post we will take up function expression & anonymous functions.