Learning TypeScript–Functions–Part 2

Dec 9th, 2012 | By | Category: Programming & Languages

Functions are one of the most important and powerful feature in Javascript and Typescript being a superset of the same, provides additional features related to functions on top of that.Let’s start with the simple function definition which is quite same as in javascript.

image

TypeScript provides us the static type checking capability.So the function parameters & return types can have datatypes as shown below:

image

There is a specific datatype in TypeScript i.e. void which can be applied only for function return types.

image

TypeScript also support function to have optional parameters. The optional parameters are followed by a question mark(?) as shown below.

image

Also, we can avoid this “if” block by providing an initializer to the optional parameter as shown below:

image

The TypeScript compiler will add the “if” block in generated Javascript code as shown below:

image

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”.

image

The trick is again done by the TypeScript compiler in similar way:

image

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.

image

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:

image

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.


Kick It on DotNetKicks.com
Tags: ,