How to Add a Return Type to a Function in TypeScript


How can we add a return type to a function in TypeScript?

Suppose we have an interface User.

interface User {
  id: string,
  name: string
};

Let’s see how we can return a User from a function in TypeScript.

Add return type in arrow function form

The return type will come after the closing parenthesis of the parameters.

const returnUser = (text: string): User => {
  // Return a User
}

Add return type in function declaration form

The same goes for functions declared in this form.

function returnUser (text: string): User {
  // Return a User
}