Typescript Foundations / Functions

Function parameter and return type annotation

πŸ‘‰ Type annotations help TypeScript check inputs and outputs of a function.

πŸ‘‰ They act as self-documentation and prevent bugs from invalid arguments or return types.


βœ… Function Parameter Type Annotation

You can specify the type of each parameter like this:

function greet(name: string, age: number) {
  console.log(`Hello ${name}, you are ${age} years old.`);
}

greet("Alice", 25);   // βœ…
greet(123, "Bob");    // ❌ Error: Argument types don't match

βœ… Return Type Annotation

Use : <type> after the parameter list to declare the return type:

function add(a: number, b: number): number {
  return a + b;
}

πŸ” If the function doesn’t return anything, use void:

function logMessage(msg: string): void {
  console.log(msg);
}

πŸ‘‰Optional vs Default Parameters

βœ… Optional Parameter

πŸ‘‰ An optional parameter doesn’t have to be passed when the function is called.

πŸ‘‰ Use ? after the parameter name to make it optional.

function greet(name: string, age?: number): string {
  if (age !== undefined) {
    return `Hello, ${name}. You are ${age} years old.`;
  }
  return `Hello, ${name}.`;
}

greet("Alice");       // βœ… OK
greet("Alice", 25);   // βœ… OK

🧠 Notes:

  • Optional parameters must come after required parameters.

function wrongExample(age?: number, name: string) {} // ❌ Error

βœ… Default Parameter

πŸ‘‰ Default parameters provide a fallback value if no argument is provided.

πŸ‘‰ Use = in the function signature to assign a default.

function greet(name: string = "Guest"): string {
  return `Hello, ${name}`;
}

greet();            // "Hello, Guest"
greet("Codeveda");  // "Hello, Codeveda"

You can combine default and optional parameters too:

function sendMessage(msg: string = "Hello", to?: string) {
  console.log(`${msg}${to ? " to " + to : ""}`);
}

sendMessage();                  // "Hello"
sendMessage("Hi", "Codeveda");  // "Hi to Codeveda"

⚠ Why annotate return types?

TypeScript usually infers the return type, but explicitly declaring it:

  • Makes the function signature clear

  • Catches bugs when the return type is wrong or missing

  • Helps with large teams or public APIs



πŸ’‘ Summary

What

Syntax

Parameter type

function f(x: string)

Return type

: number after params

No return

: void

Optional param

x?: number

Default value

x: number = 10


βœ… Example Function Signature (all-in-one)

function calculateTax(amount: number, rate: number = 0.18): number {
  return amount * rate;
}