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.

Frequently asked questions

How does Python handle return type?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Type Hints for Functions" snippet in Python uses `def func(param: Type) -> ReturnType:`.
Which code does the Python example use?
The "Type Hints for Functions" snippet uses `def func(param: Type) -> ReturnType:`, from the Functions section of the Python cheat sheet.
Which stacks cover "return type" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Hints for Functions": Use collections.abc.Callable for function type hints. The format is Callable[[ArgTypes], ReturnType]. For complex signatures, consider typing.Protocol.