Return type annotations
You write `: type` after a function's parentheses to say what type of value it returns.
A return type annotation goes between the ) of the parameters and the { of the body. In function greet(name: string): string, the second string is what greet returns.
The type checker (tsc) does two things with it: it checks that every return in the function matches that type, and it tells callers what they will get back. If you change the body by mistake, the error shows up in the function, not far away from it.
TypeScript can also infer the return type. Still, the course writes it on exported functions, because it works as a visible contract: you read the signature without opening the body.
The annotation is gone when Node runs the code: Node strips the types and only the function remains.
function double(n: number): number {
return n * 2;
}
Reach for it when: Reach for it on exported or public functions, to fix the contract of what they return. Also when you want a wrong `return` to fail inside the function itself.
Examples
Common mistake
function age(birth: number): number {
return String(2025 - birth);
}
console.log(age(2000));Why: The function promises `number`, but the `return` gives a `string`. tsc rejects it.
How to write it: Return a number: return 2025 - birth;, or change the annotation if you really want a string.
Common mistake
function label(n: number): string {
if (n > 0) {
return "positive";
}
}
console.log(label(1));Why: If `n` is not above 0, the function ends with no `return` and would give `undefined`, which is not a `string`.
How to write it: Return a value on every path, for example return "not positive"; at the end.
