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

September 15, 2021 - 2 min read

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

TL;DR

// simple function with return
// value of number array type
function getNumbers(): number[] {
  return [1, 2, 3];
}

For example, let's say we have a function called getNumbers() and on calling the function should return an array containing only numerical values for example 1, 2, 3, etc.

It can be done like this,

// simple function
function getNumbers() {
  return [1, 2, 3];
}

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

// simple function with return
// value of number array type
function getNumbers(): number[] {
  return [1, 2, 3]; // ✅ allowed
}

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

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

// simple function with return
// value not of number array type
function getNumbers(): number[] {
  return ["Hi", "Hello"]; // ❌ not allowed. Type 'string' is not assignable to type 'number'.
}

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 'string' is not assignable to type 'number'. 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 😃.