Function Return Types
In this page:
Returning Numbers
Writing : number after the parameter list tells TypeScript exactly what type a function should return, for example function add(a: number, b: number): number. Any return statement inside the function that produces something other than a number becomes a compile-time error.
Example: Returning Numbers
function add(a: number, b: number): number {
return a + b;
}
console.log(add(4, 5));
Returning Strings
Use : string when a function is meant to always produce text, such as formatting a name or building a message. This return type also lets callers rely on string methods on the result without needing an extra type check.
Example: Returning Strings
function formatName(first: string, last: string): string {
return `${first} ${last}`;
}
console.log(formatName("Ada", "Lovelace"));
Returning Booleans
Boolean return types are especially useful for functions that answer a yes-or-no question, like isValid or hasPermission. Declaring : boolean makes it clear at a glance, and to the compiler, exactly what kind of answer the function gives.
Example: Returning Booleans
function isValid(age: number): boolean {
return age >= 18;
}
console.log(isValid(20));
Void Return Type
Use void as the return type when a function performs an action, like logging or mutating something, but doesn't produce a value the caller should use. It signals that any value the function does return is not meant to be relied upon.
Example: Void Return Type
function logAction(action: string): void {
console.log(`Action: ${action}`);
}
logAction("Saved");
Why Return Types Matter
Explicit return types document exactly what a function produces, which helps both human readers and the compiler. They catch accidental mistakes, like a code path that falls through and returns undefined when every other path returns a real value.
Example: Why Return Types Matter
function getStatus(active: boolean): string {
if (active) return "Active";
// Forgetting to return here would be a compiler error, not a silent bug
return "Inactive";
}
console.log(getStatus(true));
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: