Functions
Functions
The TypeScript type system pays a lot of love to functions, after all they are the core building blocks of a composable system.
Parameter annotations
Of course you can annotate function parameters just like you can annotate other variables:
Here I used inline type annotations. Of course you can use interfaces etc.
Return type annotation
You can annotate the return type after the function parameter list with the same style as you use for a variable, e.g. : Foo
in the below example:
Of course I used an interface
here, but you are free to use other annotations e.g. inline annotations.
Quite commonly you don't need to annotate the return type of a function as it can generally be inferred by the compiler.
However, it is generally a good idea to add these annotation to help with errors e.g.:
If you don't plan to return anything from a function, you can annotate it as :void
. You can generally drop :void
and leave it to the inference engine though.
Optional Parameters
You can mark a parameter as optional:
Alternatively you can even provide a default value (using = someValue
after the parameter declaration) which is injected for you if the caller doesn't provide that argument:
Overloading
TypeScript allows you to declare function overloads. This is useful for documentation + type safety purpose. Consider the following code:
If you look at the code carefully you realize the meaning of a
,b
,c
,d
changes based on how many arguments are passed in. Also the function only expects 1
, 2
or 4
arguments. These constraints can be enforced and documented using function overloading. You just declare the function header multiple times. The last function header is the one that is actually active within the function body but is not available to the outside world.
This is shown below:
Here the first three function headers are available as valid calls to padding
:
Of course it's important for the final declaration (the true declaration as seen from inside the function) to be compatible with all the overloads. This is because that is the true nature of the function calls that the function body needs to account for.
Function overloading in TypeScript doesn't come with any runtime overhead. It just allows you to document the manner you expect the function to be called in and the compiler holds the rest of your code in check.
Last updated