Return type

2 snippets across 2 stacks — Python, TypeScript

PYPython

Type Hints for Functions

PY · Functions
syntax
def func(param: Type) -> ReturnType:
example
from collections.abc import Callable

def apply(
    values: list[int],
    transform: Callable[[int], int]
) -> list[int]:
    return [transform(v) for v in values]

result = apply([1, 2, 3], lambda x: x * 10)
print(result)
output
[10, 20, 30]

Note Use collections.abc.Callable for function type hints. The format is Callable[[ArgTypes], ReturnType]. For complex signatures, consider typing.Protocol.

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.