Functions in TypeScript
Build robust functions that scale
The aim of this article is to show which features TypeScript provides for writing maintainable and reusable functions.
Functions are the fundamental building blocks of an application. A function is an action that performs a certain behavior like login the user, showing a list of items, requesting data from the server, and so forth. These actions together compose a system to solve various tasks.
In mathematics, a function is described as an object that produces an output when given an input. While in programming we have two types of functions. A function that returns a value, or one that doesn’t return anything. For instance if you need the result like the sum of two numbers, we need to return the total value. And if you need to print out a message to the console, a return type is not necessary.
If you are looking for code examples, go to section 4.
Here’s What We’ll Address
- Why TypeScript?
- Do we really need types?
- Typed parameters (example)
- Optional parameters (example)
- Overload parameters (example)
- The benefits of learning TypeScript
1. Why TypeScript?
You may ask: “Why do we need types?”
Let us pretend we send an email without a subject to someone. Now, in order to understand the mail, the receiver has to open it and read the text. This adds unnecessary time and overhead for something that could easily be prevented if the sender had defined the subject beforehand.
However, for one mail this is not an issue, but with thousands one can start to count the amount of time and resources it takes for receivers to read the content.
The same concept applies for developers when learning code, imagine having many classes, functions, objects, methods, variables, and so forth with no types. No labels that describes the data. And the only way to understand it: the developer has to contact the author, open the source code, or perform tests. This is not a intuitive approach for efficient programming.
TypeScript helps to prevent such scenarios with types, the developer doesn’t have to guess or predict what properties an object has.
For instance, if a developer writes
const name = 'Bob Marley', the JS engine (parser) determines the type by reading the data, in this case the value
Bob Marley is a type of
string. However, even though the type is defined, one can still assign a number, object or a function to the
3. Do We Really Need Types?
When using existing functions in a small or large applications, the questions are often: “What arguments does this function accept or what does it return?”
TypeScript solves such questions through defining types for arguments (input) and the return statement (output) in an intuitive way. Leaving misunderstanding and confusion out of the picture, with this, a developer can quickly determine how to interact or reuse a function.
As shown in the example above, the function accepts two arguments and returns the result, which is
Now, if we run the code, we won't get any errors because the code does what it is intended to do — add two values regardless of type.
+ sign means concatenate which is commonly used when we want to compose text with values like
'Hi' + firstName. This type of behavior is not something we want scattered throughout our application.
Note: Lack of types makes it difficult for the developer to work efficiently, too much overhead where the developer must manually look at the source code and documentation to understand things that can take seconds in TypeScript.
Second example (TypeScript)
Now, if you pass a number and a string as we did earlier, it throws a type error because it only accepts arguments of type
number. This is good news! It means we have the power reduce bugs, and have a secure app that is explicit.
4. Typed Parameters
5. Optional Parameters
As shown, by adding a
? sign to the end of parameter, we mark it as optional.
Did you know: An optional parameter must be defined after a required parameter, otherwise it returns an error message:
A required parameter cannot follow an optional parameter.
If no arguments are passed, it sets the value to undefined. But what if we want to set a default value? It seems non-intuitive to have
sold set to undefined by default whenever we add a new car right? Here’s how to fix it:
Now, every time we create a new car, the
sold variable is set to
false by default. Notice we are not using the optional parameter sign like
boolean: sold because TypeScript handles the type automatically.
6. Overload Parameters
Sometimes we want a function to do one thing, and other times do more based on arguments we pass (overload parameters). It is useful concept that can create abstract layers when dealing with functions with many behaviors.
Let’s see an example of overload parameter:
As shown in the example above, the function
runEngines() uses the
typeof keyword to check the argument type to define what operation to execute. Notice that the function
function runEngines(x): any must be defined last because it’s a universal function that represents all possibilities defined in the functions above.
This approach is not recommended thus a function ends up with multiple behavior which makes it difficult to maintain and reuse, a feasible approach would be dividing the behavior into separate functions which is seen as a good practice in programming. However, in some scenarios such approach may be necessary, but that depends on the requirements.
7. The Benefits of Learning TypeScript
If you are not familiar with types, which are one of the core features TypeScript is based on, it’s essentially a label that defines the type of the data which can be a number, string, or an object.
TypeScript helps developers to quickly determine the flexibility of functions, objects, classes, variables instead of dealing with source code and documentation which consumes time and resources that can be spent on development.
TypeScript also offers a great development experience through enhanced IDE (integrated development environment) support. An IDE such Visual Studio helps developers to easily detect compilation errors, do code refactoring, and code completion (flexibility of a function). All of this so developers like me and you can spend more time on coding (adding value) and less time debugging.
TypeScript does not enforce types, but recommends it. This puts code completion on a whole new level where one can see what boundaries and data a function accepts directly.
In short, TypeScript does not imply becoming a great programmer overnight, no language can do so. But what makes it so special is the number of features and flexibility it provides to help developers produce high quality and robust code.