...

Web Technologies - TypeScript

Back to Course

Lesson Description


Lession - #1450 TypeScript Functions


Functions are the fundamental structure block of any operation in JavaScript. They ’re how you make up layers of abstraction, mimicking classes, information hiding, and modules. In TypeScript, while there are classes, namespaces, and modules, functions still play the key role in describing how to do things. TypeScript also adds some new capabilities to the standard JavaScript functions to make them easier to work with.

Function Types
Typing the function

Let’s add types to our simple example


 function add( x number, y number>
number{ return x y; } let myAdd = function( x number, y number>
number{ return x y; };


Writing the function type
Now that we ’ve typed the function, let’s write the full type of the function out by looking at each piece of the function type.


 let myAdd( x number, y number>
= > number = function( x number, y number >
number{ return x y; ;


Optional and Default Parameters
In TypeScript, every parameter is assumed to be required by the function. This does n’t mean that it ca n’t be given null or undefined, but rather, when the function is called, the compiler will check that the user has provided a value for each parameter. The compiler also assumes that these parameters are the only parameters that will be passed to the function. In short, the number of arguments given to a function has to match the number of parameters the function expects.


 function buildName( firstName string, lastName string>
{ return firstName"" lastName; let result1 = buildName(" Bob">
;// error, too many parameters Expected 2 arguments, but got 1. let result2 = buildName(" Bob"," Adams","Sr.">
;// error, too many parameters Expected 2 arguments, but got 3. let result3 = buildName(" Bob"," Adams">
;// ah, just right


Online compiler