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

Published September 11, 2021

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!";
}

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!";
}

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
}

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

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


Share on: Facebook Twitter