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

September 16, 2021 - 2 min read

To add boolean array 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 followed by [] symbol (opening and closing square brackets) to indicate that the function's return value is of boolean array type.

TL;DR

// simple function with return
// value of boolean array type
function getBooleans(): boolean[] {
  return [true, false, true];
}

For example, let's say we have a function called getBooleans() and on calling the function should return an array containing only boolean values for example true, false, true, etc.

It can be done like this,

// simple function
function getBooleans() {
  return [true, false, true];
}

This is fine. But what if we need to enforce that the return value of the getBooleans function should only return an array of booleans and nothing else. To do that we can add the function return type like this,

// simple function with return
// value of boolean array type
function getBooleans(): boolean[] {
  return [true, false, true]; // ✅ allowed
}

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

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

// simple function with return
// value not of boolean array type
function getBooleans(): boolean[] {
  return [1, 2, 3]; // ❌ not allowed. Type 'number' is not assignable to type 'boolean'.
}

As you can see from the above code the TypeScript compiler is not allowing us to return the array and shows us an error saying Type 'number' 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 😃.