name(arg: T): R Function Type Annotations
Last updated: 2026-10-22
name(arg: T): R Function Type Annotations
Function annotations declare parameter and return types: callers see at a glance what to pass and what comes back, and wrong arguments fail at compile time. Inference is a fallback, but explicit annotations are basic hygiene for public APIs.
| Group | Functions & Classes |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
// Shipping fee = base + per-kg surcharge
function shippingFee(weightKg: number, express: boolean): number {
return 8 + weightKg * (express ? 3.5 : 1.5);
}
const calc: (w: number, express: boolean) => number = shippingFee;
// No meaningful return → void
function notify(msg: string): void {
console.log(msg);
}
⚙️ Parameters
| weightKg: number | Parameter annotation: a colon and type after the name; wrong types are compile errors |
|---|---|
| ): number | Return annotation: after the parameter list; every return statement must match |
| void | Means "no meaningful return"; callers should not use the result |
Returns:The return type follows the parameter list (: number); the compiler checks each return against it. Omit it and TS infers from the body.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
Normal: 11
Express: 15
(Runtime output after transpilation; shippingFee(2, "yes") is a compile error — the second parameter must be boolean)
💡 Notes
ℹ️ Info Return types can usually be omitted (inference is smart), but exported functions should declare them explicitly — so implementation changes cannot silently alter the public contract.
⚠️ Note Parameter annotations cannot be omitted: unlike variables, standalone function parameters without annotations error under noImplicitAny — TS cannot guess what callers will pass.
💡 Tip Callback parameters need no annotations: when the variable/parameter already has a function type, the implementation parameters get types via contextual typing (see the contextual-typing entry).
🏷️ Related Functions & Classes
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q When is a return type annotation required?
A Three typical cases: exported APIs, recursive functions, and when inference is not what you want (e.g. a union gets widened). Internal functions can rely on inference.
Q Is there a difference between : void and : undefined?
A Yes. void means "return value ignored" and any function is assignable to it; undefined is a concrete type — the function must actually return undefined.
Q Can I just annotate parameters as any?
A It compiles but defeats the purpose: any disables all checking on that parameter and the return. Prefer precise types; use unknown plus narrowing when "anything" is genuinely allowed.