Defining Functions
Typing a function = typing its parameters and return
You annotate each parameter, and optionally the return type. Parameters work just like typed variables.
function add(a: number, b: number): number {
return a + b;
}
Usually, don't annotate the return type — let it be inferred
TypeScript infers the return type from the return statements, and the inferred type is often more precise than what you'd write by hand. Skip the annotation for internal functions.
function add(a: number, b: number) {
return a + b; // return type inferred as number — no need to write it
}
When you should annotate the return type
Explicit return types earn their place on public / exported functions:
- They document the contract at a glance.
- They catch bugs at the source — if the body accidentally returns the wrong thing, the error points at the function, not at some distant caller.
export function getUser(id: string): User {
// if this body returns something that isn't a User,
// the error is reported HERE, not wherever getUser is called
return db.find(id);
}
Parameters: always typed (TypeScript can't infer a caller's intent). Return type: let it infer for internal helpers; annotate it for exported API boundaries where the contract matters.