DEV Community

Cover image for How to add a number type to function return value in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

To add number 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 to indicate that the function's return value is of number type.

TL;DR

// simple function with return
// value of number type
function getNum100(): number {
  return 100;
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a function called getNum100() and on calling the function should return the number value 100.

It can be done like this,

// simple function
function getNum100() {
  return 100;
}
Enter fullscreen mode Exit fullscreen mode

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

// simple function with return
// value of number type
function getNum100(): number {
  return 100; // ✅ allowed
}
Enter fullscreen mode Exit fullscreen mode

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

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

// simple function with return
// value of number type
function getNum100(): number {
  return "Hey!"; // ❌ not allowed. Type 'string' is not assignable to type 'number'.
}
Enter fullscreen mode Exit fullscreen mode

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 '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 😃.


Discussion (0)