Categories
TypeScript

Using TypeScript — Function Return Values and Overloads

Spread the love

TypeScript is a natural extension of JavaScript that’s used in many projects in place of JavaScript.

However, not everyone knows how it actually works.

In this article, we’ll look at how to control function return values and overloads.

Disabling Implicit Returns

JavaScript is very flexible with its return types.

JavaScript functions return undefined if the function doesn’t have an implicit return statement.

This is known as the implicit return feature.

To prevent implicit returns, we can set the noImplicitReturns in compilerOptions to true .

This way, if there are paths through functions that don’t explicitly produce a result with the result keyword, an error would be thrown.

If we disable implicit returns, then we’ve to be explicit about what we return.

For instance, if we have a parameter that can be null :

const getTax = (price: number | null, ...fees: number[]): number => {
  return price * 0.2 - fees.reduce((total, fee) => total + fee, 0);
};

Then we’ll get a warning about price being possibly null from the compiler.

To fix the error, we’ve to make the returns explicit.

For instance, we can write:

const getTax = (price: number | null, ...fees: number[]) => {
  if (price !== null) {
    return price * 0.2 - fees.reduce((total, fee) => total + fee, 0);
  }
  return undefined;
};

We added a null check for price and return undefined is it’s null .

Void Functions

Functions that don’t return anything have a void return type.

For instance, we can define a void function by writing:

const greet = (): void => {
  console.log("hello");
};

Since our function returns nothing, we use void to denote that.

Overloading Function Types

With TypeScript, we can overload functions.

This means that we can define multiple functions for the function with the same name.

For instance, we can write:

function getTax(price: number): number;
function getTax(price: null): number;
function getTax(price: number | null): number {
  if (price !== null) {
    return price * 0.2;
  }
  return 0;
}

Now we can take a number parameter or null parameter when we call getTax .

The overloads only provide information about the various signatures to the TypeScript compiler.

It will be combined into one function in the built JavaScript code that we actually run.

Conclusion

With TypeScript, just like JavaScript, implicit returns undefined if no return statement is specified explicitly.

We can make the TypeScript compiler avoid implicit returns with the noImplicitReturns option set to true .

TypeScript lets us define multiple function signatures for the same function.

This let us accept different kinds of data within one function and express that in a clear way.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *