How to add a boolean type to function return value in TypeScript?

Published September 13, 2021

To add boolean type to function return value first, declare the function, then add a : symbol (colon) after the parameters opening and closing brackets () and then type the word boolean to indicate that the function's return value is of boolean type.

TL;DR

// simple function with return
// value of boolean type
function isPerson(): boolean {
  return true;
}

For example, let's say we have a function called isPerson() and on calling the function should return the boolean value true.

It can be done like this,

// simple function
function isPerson() {
  return true;
}

This is fine. But what if we need to enforce that the return value of the isPerson function should only return the value of the boolean type. To do that we can add the function return type like this,

// simple function with return
// value of boolean type
function isPerson(): boolean {
  return true; // ✅ allowed
}

After defining the return type as a boolean, we must return a value of the boolean type or it may show an error.

Now Let's also try to return a value other than the boolean type like this,

// simple function with return
// value not of boolean type
function isPerson(): boolean {
  return "Hey!"; // ❌ not allowed. Type 'string' is not assignable to type 'boolean'.
}

As you can see from the above code the TypeScript compiler is not allowing us to return the value and shows us an error saying Type 'string' is not assignable to type 'boolean'. which is what we want to happen.

See the above codes live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter