TypeScript Return Type of Function: How to Specify, Infer, and Use Them

Do you want to know how to specify the return type of a function in TypeScript properly? Or wondering why your TypeScript function is throwing type errors even though the logic seems correct?

In this tutorial, I’ll walk you through everything you need to know about function return types in TypeScript. I’ll show you how to specify them, let TypeScript infer them, and when it’s best to use each approach.

What is a Function Return Type in TypeScript?

In TypeScript, the return type of a function specifies what kind of value the function will return. This can be a primitive type like string, number, or boolean, or a more complex type like an object, array, or even a union of types.

By explicitly declaring return types, you help TypeScript catch bugs early and make your code easier to understand for anyone who reads it, including your future self!

One of the advantages of specifying the return type of a function in TypeScript is that it will warn you if your function tries to return the wrong type.

Check TypeScript ?? Operator

Implicit vs Explicit Return Types

TypeScript is smart enough to infer return types in many cases, but explicitly declaring them has several benefits:

// Implicit return type (inferred as number)
function calculateAge(birthYear: number) {
  return new Date().getFullYear() - birthYear;
}

// Explicit return type
function calculateAge(birthYear: number): number {
  return new Date().getFullYear() - birthYear;
}

While both functions work the same way, the explicit return type:

  • Acts as documentation
  • Prevents accidental changes to the return type
  • Makes the code more self-documenting
  • Helps catch errors if your implementation changes

Check out How to Append to Arrays in TypeScript

Method 1: Explicitly Specifying the Return Type

The most straightforward way to set a return type in TypeScript is to declare it right after the parameter list, using a colon.

function getSalesTax(amount: number): number {
    return amount * 0.07; // 7% sales tax, typical in many U.S. states
}

Here, : number tells TypeScript that getSalesTax must return a number. If you accidentally return a string or another type, TypeScript will immediately alert you.

Example: Returning an Object

Let’s say you’re working on a function that returns details about a U.S. customer:

function getCustomer(id: number): { name: string; state: string } {
    // Simulate fetching data
    return { name: "Jane Doe", state: "California" };
}

By specifying the object shape, you make it clear what to expect.

Here is another example:

You can return custom object types:

interface Customer {
  id: number;
  name: string;
  email: string;
  state: string;
}

function createNewCustomer(name: string, email: string): Customer {
  return {
    id: Math.floor(Math.random() * 10000),
    name,
    email,
    state: 'CA' // Default state
  };
}

Example: Array Return Types

There are two ways to define array return types:

// Method 1
function getUSStates(): string[] {
  return ['Alabama', 'Alaska', 'Arizona', /* ... other states */];
}

// Method 2 (equivalent)
function getUSStates(): Array<string> {
  return ['Alabama', 'Alaska', 'Arizona', /* ... other states */];
}

Method 2: Letting TypeScript Infer the Return Type

Sometimes, TypeScript can figure out the return type on its own—this is called type inference. If your function is simple and the return value is obvious, you can leave off the return type.

function getStateAbbreviation(state: string) {
    return state.slice(0, 2).toUpperCase();
}

TypeScript knows this function returns a string, so you don’t have to specify it. This makes your code a bit cleaner, but be cautious—if your function logic gets more complex, specifying the return type can prevent subtle bugs.

Check out Import JSON Files in TypeScript

Method 3: Using Union Types as Return Types

There are times when a function might return more than one type. For example, let’s say you’re looking up a ZIP code and returning either the city name or null if not found.

function getCityByZip(zip: string): string | null {
    const zipDatabase: { [key: string]: string } = {
        "10001": "New York",
        "90001": "Los Angeles",
        "60601": "Chicago",
    };
    return zipDatabase[zip] || null;
}

Here, string | null is a union type, indicating the function can return either a string or null. This is especially helpful when dealing with optional data or error handling.

Method 4: Returning Promises (Async Functions)

Modern applications often fetch data asynchronously. In TypeScript, you can specify that a function returns a Promise of a certain type.

async function fetchUserData(userId: number): Promise<{ id: number; name: string }> {
    // Simulate an API call
    return { id: userId, name: "Alex Smith" };
}

TypeScript enforces that the resolved value of the Promise matches the specified type, making your async code more predictable.

Read TypeScript Enum vs Const

Method 5: Using Type Aliases and Interfaces for Return Types

For more complex return values, especially objects with many properties, it’s best to define a type alias or interface.

interface Product {
    id: number;
    name: string;
    price: number;
    inStock: boolean;
}

function getProduct(productId: number): Product {
    return {
        id: productId,
        name: "iPhone 15 Pro",
        price: 999,
        inStock: true,
    };
}

This keeps your code organized and makes it easy to reuse types across multiple functions.

Method 6: Functions with No Return Value (void)

Some functions perform actions but don’t return anything. In TypeScript, you can use the void return type.

function logPurchase(productId: number, userId: number): void {
    console.log(`User ${userId} purchased product ${productId}`);
}

If you accidentally return a value from a void function, TypeScript will let you know.

Method 7: Functions That Never Return (never)

Occasionally, you’ll write functions that never return—typically because they always throw an error or have infinite loops. TypeScript uses the never type for these:

function throwError(message: string): never {
    throw new Error(message);
}

This is useful for functions that handle critical errors or assertions.

Check out TypeScript Enum with Multiple Values

TypeScript Return Type of Function Example: U.S. Sales Tax Calculator

Let’s put all this together in a practical example relevant to the USA: a function that calculates the total price after sales tax, returning either the new total or an error message.

type CalculationResult = { total: number } | { error: string };

function calculateTotalWithTax(amount: number, state: string): CalculationResult {
    const stateTaxRates: { [key: string]: number } = {
        "CA": 0.0725,
        "NY": 0.04,
        "TX": 0.0625,
    };

    const taxRate = stateTaxRates[state];

    if (taxRate === undefined) {
        return { error: "State not supported" };
    }
    const total = amount + amount * taxRate;
    return { total: parseFloat(total.toFixed(2)) };
}
const amount = 100;
const state = "CA"; // Try "NY", "TX", or an unsupported state like "FL"

const result = calculateTotalWithTax(amount, state);

if ("total" in result) {
    console.log(`Total amount for $${amount} in ${state}: $${result.total}`);
} else {
    console.log(`Error: ${result.error}`);
}

Here, we use a type alias for the return value to make it clear what the function can return. This pattern is especially useful for real-world applications.

You can see the exact code in the screenshot below:

TypeScript Return Type of Function

In this tutorial, I explained everything about the TypeScript Return Type of a Function with various examples. Do let me know if you still have any questions.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App