Functions in TypeScript

Build robust functions that scale

Dler Ari
Dler Ari
Dec 3 · 7 min read
https://unsplash.com/photos/wpU4veNGnHg

The aim of this article is to show which features TypeScript provides for writing maintainable and reusable functions.

“TypeScript enable JavaScript developers to use highly-productive development tools and practices like static checking and code refactoring when developing JavaScript applications.” Source.

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

  1. Why TypeScript?
  2. TypeScript does not replace JavaScript
  3. Do we really need types?
  4. Typed parameters (example)
  5. Optional parameters (example)
  6. Overload parameters (example)
  7. 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.

The core difference that separates TypeScript from Javascript is types, here’s a simple example showing what happens if we assign a text to a number:

JavaScript vs. TypeScript

2. TypeScript Does Not Replace JavaScript

It is important to realize that TypeScript is a superset of JavaScript. It does not replace JavaScript, but extends it by enabling optional types (type annotations), and many more features to help developers create clean, readable, and maintainable functions that scale.

JavaScript is a dynamic language where types are defined by the browser engine (run-time), while in TypeScript, the developer has the flexibility to define types early when writing code. This means the compiler can detect most of the bugs before they enter production.

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 name variable without receiving any type errors. Many would argue that this is strange behavior while others say that this is aligned with JavaScript’s dynamic nature.

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.

Note: The goal of TypeScript is not to limit the developer to write less JavaScript code, but improve the understanding of stuff.

Below, we have two code examples. The first shows a function without types (typical in JavaScript), and the second with types (typical in TypeScript):

First example (JavaScript)

JavaScript example

As shown in the example above, the function accepts two arguments and returns the result, which is 10hello.

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.

In JavaScript, the + 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)

TypeScript example

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.

Note: The goal is not to have everything typed, we still want to use the dynamic nature of JavaScript, but we need to make sure that functions or classes are correctly used by other developers.

4. Typed Parameters

In TypeScript, the number of arguments passed to a function has to be equal to the number of parameters the function expects. Whereas in JavaScript, a function can accept as many arguments as possible:

Type parameters in TypeScript

5. Optional Parameters

Function parameters in TypeScript are not optional by default as they are in JavaScript. Optional parameters are great when values at a certain moment are not present:

Optional Parameters in TypeScript

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:

Default value in TypeScript

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:

Overload Parameters in TypeScript

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

Writing functions in JavaScript is generally easy, but once we add more lines of code and team members, it becomes difficult to maintain and reuse, thus lack of types.

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.

Most developers familiar with JavaScript libraries (NPM packages) have been in the scenario where lots of reading is required to understand the possibilities of a function like what methods or properties are available etc.

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.

Summary

TypeScript is not a replacement for JavaScript, but simply a language helping developers to build more maintainable and reusable code, like functions. They can spend more time coding 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.

All in all, TypeScript allows a significant gain in productivity compared to dealing with JavaScript.

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.

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Dler Ari

Written by

Dler Ari

A Computer Engineer covering the web ecosystem.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade