Return Types
Annotate what a function gives back, or let TypeScript infer it.
Syntax
function name(): string { return "hi"; }You can annotate a function's return type after the parameter list. TypeScript checks that every return matches it.
Return types are often inferred automatically, but writing them explicitly documents intent and catches mistakes where the body returns the wrong thing.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A public API module annotates all function return types as documentation so consumers know what to expect.
- A data-fetching function is annotated as returning Promise<User[]> so callers handle the async result correctly.
- A team enforces explicit return types in their linting config to prevent accidental any inference in utility functions.
More examples
Explicit return type annotation
Adds explicit return type annotations after the parameter list, serving as both documentation and a compiler check.
function add(a: number, b: number): number {
return a + b;
}
function fullName(first: string, last: string): string {
return `${first} ${last}`;
}Return type mismatch error
Shows the compile error when a function's return value does not match its declared return type.
function getCount(): number {
return 'many'; // Error: Type 'string' is not assignable to type 'number'
}Async function return type
Types an async function's return as Promise<User>, propagating the typed value through the await chain.
interface User { id: number; name: string; }
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json() as User;
}
async function main(): Promise<void> {
const user = await fetchUser(1); // user: User
console.log(user.name);
}
Discussion