Functions are the core building blocks of any JavaScript or TypeScript application.
TypeScript allows you to strictly define the types for both inputs and outputs.
This ensures functions are always called with the correct number and type of arguments.
It makes debugging a breeze and drastically reduces runtime crashes.
To type a parameter, add a colon and the type directly after the parameter name.
To type the return value, add a colon and the type after the closing parenthesis.
If a function returns nothing, you explicitly type its return value as void.
function addNumbers(a: number, b: number): number {
return a + b;
}
let sum = addNumbers(10, 5); // Works perfectly
// addNumbers("10", 5); // Error: Argument is not a number
console.log("Sum:", sum);
Just like object properties, you can make function parameters optional using a ?.
You can also provide default values directly in the parameter list.
Optional parameters must always come after required parameters in the list.
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greet("Akash")); // Uses default logic
Explicitly typing function returns speeds up the TypeScript compilation process.
It serves as perfect, self-documenting code for new team members.
High-quality documentation and maintainability naturally lead to better project success.
function logToDatabase(message: string): void {
console.log("Saving: " + message);
// Does not return a value
}
logToDatabase("User profile");
Where do you place the return type annotation in a function declaration?
Properly typing your functions is the single best habit you can form in TypeScript.
It provides immediate feedback if you misuse a function anywhere in your app.
Next, we will learn how to manually override types using Casting.