Function return type

2 snippets in TypeScript

TSTypeScript

Return Type Annotations

TS · Type Annotations
syntax
function fn(): ReturnType { ... }
const fn = (): ReturnType => { ... };
example
function findUser(id: string): User | undefined {
  return userDatabase.get(id);
}

// Arrow function return type
const formatCurrency = (amount: number): string => {
  return `$${amount.toFixed(2)}`;
};

// Async function
async function fetchOrder(id: string): Promise<Order> {
  const resp = await fetch(`/api/orders/${id}`);
  return resp.json();
}
output
// Async functions always return Promise<T>

Note Explicit return types are especially valuable for public API functions, async functions, and functions with multiple return paths. They also speed up type-checking in large projects since the compiler does not need to analyze the function body.

ReturnType & Parameters

TS · Utility Types
syntax
type Ret = ReturnType<typeof fn>;
type Params = Parameters<typeof fn>;
example
function createOrder(userId: string, items: string[], coupon?: string) {
  return {
    orderId: `ord_${Date.now()}`,
    userId,
    items,
    discount: coupon ? 0.1 : 0,
  };
}

type OrderResult = ReturnType<typeof createOrder>;
// { orderId: string; userId: string; items: string[]; discount: number }

type OrderParams = Parameters<typeof createOrder>;
// [userId: string, items: string[], coupon?: string]
output
// ReturnType extracts what the function returns; Parameters extracts the argument tuple

Note Both require typeof when used with a concrete function (not a type). For class constructors, use ConstructorParameters<typeof ClassName>. ReturnType is invaluable for inferring types from existing functions without duplicating definitions.