DEV Community

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

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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

TL;DR

// simple function with return
// value of string type
function greet(): string {
  return "Hello!";
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a function called greet() and on calling the function should return the string value Hello World!.

It can be done like this,

// simple function
function greet() {
  return "Hello!";
}
Enter fullscreen mode Exit fullscreen mode

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

// simple function with return
// value of string type
function greet(): string {
  return "Hello!"; // βœ… allowed
}
Enter fullscreen mode Exit fullscreen mode

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

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

// simple function with return
// value of string type
function greet(): string {
  return 1; // ❌ not allowed. Type 'number' is not assignable to type 'string'.
}
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 'number' is not assignable to type 'string'. 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)