← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 5 of 10

Function Return Types

A function return type tells TypeScript what type of value a function should return. Writing return types can make function behavior clearer and help detect incorrect return values.

Returning Numbers

Writing : number after the parameter list tells TypeScript exactly what type a function should return, for example function add(a: number, b: number): number. Any return statement inside the function that produces something other than a number becomes a compile-time error.

Example: Returning Numbers

typescript
function add(a: number, b: number): number {
  return a + b;
}
console.log(add(4, 5));

Returning Strings

Use : string when a function is meant to always produce text, such as formatting a name or building a message. This return type also lets callers rely on string methods on the result without needing an extra type check.

Example: Returning Strings

typescript
function formatName(first: string, last: string): string {
  return `${first} ${last}`;
}
console.log(formatName("Ada", "Lovelace"));

Returning Booleans

Boolean return types are especially useful for functions that answer a yes-or-no question, like isValid or hasPermission. Declaring : boolean makes it clear at a glance, and to the compiler, exactly what kind of answer the function gives.

Example: Returning Booleans

typescript
function isValid(age: number): boolean {
  return age >= 18;
}
console.log(isValid(20));

Void Return Type

Use void as the return type when a function performs an action, like logging or mutating something, but doesn't produce a value the caller should use. It signals that any value the function does return is not meant to be relied upon.

Example: Void Return Type

typescript
function logAction(action: string): void {
  console.log(`Action: ${action}`);
}
logAction("Saved");

Why Return Types Matter

Explicit return types document exactly what a function produces, which helps both human readers and the compiler. They catch accidental mistakes, like a code path that falls through and returns undefined when every other path returns a real value.

Example: Why Return Types Matter

typescript
function getStatus(active: boolean): string {
  if (active) return "Active";
  // Forgetting to return here would be a compiler error, not a silent bug
  return "Inactive";
}
console.log(getStatus(true));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.