Annotate function parameters and return types so callers get safe, predictable results.
What you will see
done
About 2 min of reading
Quick check
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Try It
Function parameter and return annotations document intent and are stripped at runtime. Try typed functions with optional, default, `void`, and `never` return types.
1
Declaring parameter and return types
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));
Before you run it, say out loud what it will print. Then open the answer.
Before you run it, say out loud what it will print. Then open the answer.
What it prints
Hi, Ada
Hello, Ada
3
Void and never
function log(msg: string): void {
console.log(msg);
}
log("done");
Before you run it, say out loud what it will print. Then open the answer.
What it prints
done
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
A caller passes typed arguments; the function runs and returns a typed value the caller can trust.
1Call function with arguments -> checked against parameter types
↓
2Body executes -> return statements checked against return type
↓
3Function returns a value -> caller receives the declared type
↓
4Caller uses it -> further type safety preserved
Why this worksWhy annotate return types
The compiler can infer return types, but explicit annotations document intent and catch regressions:
functionparse(input: string): number {
const n = Number(input);
if (isNaN(n)) return0; // explicit fallbackreturn n;
}
Without the : number annotation, a stray early return of a string would be a type error, the annotation forces every path to return a number.
Function parameter shapes
Complex parameters become interfaces or inline object types:
Inline object types keep small configs local; extracted interfaces are better for reused shapes. Always mark truly optional properties with ? so callers can skip them.
Examples
Declaring parameter and return types
Typed functions
functionadd(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3)); // 5
The : number after the parameters declares the return type. The compiler checks the body actually returns a number and that callers pass numbers.