TypeScript Functions

Functions are the building blocks of any program. A function groups a set of instructions under one name, makes it reusable, and keeps code organized. TypeScript enhances JavaScript functions by adding types to parameters and return values, making functions predictable and safe to use across large codebases.

Function Anatomy in TypeScript

  function calculateTotal(price: number, tax: number): number {
      |          |              |                 |        |
      |          |              |                 |        +-- Return type
      |          |              +-------+---------+
      |          |                      |
      |          |               Typed parameters
      |          +-- Function name
      +-- Keyword
  }

Declaring a Function

A basic typed function declaration specifies types for each parameter and the return type after the closing parenthesis.

function greetStudent(name: string, course: string): string {
    return "Hello " + name + ", welcome to " + course + "!";
}

let message = greetStudent("Anjali", "TypeScript");
console.log(message);
// Output: Hello Anjali, welcome to TypeScript!

Void Return Type

Functions that perform an action without returning data use the void return type.

function showWelcome(name: string): void {
    console.log("Welcome, " + name + "!");
    // No return statement required
}

showWelcome("Rohit");
// Output: Welcome, Rohit!

Optional Parameters

Adding a question mark ? after a parameter name makes it optional. An optional parameter can be omitted when calling the function. Its value becomes undefined when not provided.

function createProfile(name: string, age?: number): string {
    if (age !== undefined) {
        return name + " | Age: " + age;
    }
    return name + " | Age: Not provided";
}

console.log(createProfile("Meera", 28));
// Output: Meera | Age: 28

console.log(createProfile("Kabir"));
// Output: Kabir | Age: Not provided

Default Parameter Values

A parameter can have a default value. When the caller does not provide that argument, the function uses the default value automatically.

function calculateDiscount(price: number, discount: number = 10): number {
    return price - (price * discount / 100);
}

console.log(calculateDiscount(1000));
// Uses default discount of 10%
// Output: 900

console.log(calculateDiscount(1000, 20));
// Uses provided discount of 20%
// Output: 800

Rest Parameters

A rest parameter collects all remaining arguments into an array. It uses three dots ... before the parameter name and must be the last parameter in the function.

function addAllMarks(subject: string, ...marks: number[]): string {
    let total = 0;
    for (let mark of marks) {
        total += mark;
    }
    return subject + " Total: " + total;
}

console.log(addAllMarks("Science", 85, 90, 78));
// Output: Science Total: 253

console.log(addAllMarks("Math", 95, 88, 92, 97));
// Output: Math Total: 372

Function Types

In TypeScript, functions themselves have types. A function type describes what parameters the function accepts and what it returns. This is useful when storing functions in variables or passing them as arguments.

// Defining a function type
let operate: (a: number, b: number) => number;

// Assigning a function that matches the type
operate = function(x: number, y: number): number {
    return x + y;
};

console.log(operate(10, 5)); // 15

// Reassign with a different implementation
operate = function(x: number, y: number): number {
    return x * y;
};

console.log(operate(10, 5)); // 50

Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They use the => symbol and work identically to regular functions for most use cases.

// Regular function
function square(n: number): number {
    return n * n;
}

// Arrow function — same result, shorter syntax
const squareArrow = (n: number): number => n * n;

console.log(square(6));       // 36
console.log(squareArrow(6));  // 36

Arrow Function Syntax Variations

// Multi-line arrow function
const greet = (name: string): string => {
    let message = "Hello, " + name;
    return message;
};

// Single-expression arrow function (implicit return)
const double = (n: number): number => n * 2;

// No parameters
const getYear = (): number => 2025;

console.log(greet("Tanya"));  // Hello, Tanya
console.log(double(7));       // 14
console.log(getYear());       // 2025

Function Overloads

Function overloads allow one function to handle different combinations of parameter types. TypeScript selects the correct behavior based on the arguments passed.

// Overload signatures (no body)
function display(value: string): string;
function display(value: number): string;

// Implementation signature (handles all overloads)
function display(value: string | number): string {
    if (typeof value === "string") {
        return "Text: " + value.toUpperCase();
    }
    return "Number: " + value.toFixed(2);
}

console.log(display("hello"));  // Text: HELLO
console.log(display(3.7));      // Number: 3.70

Parameter Types Comparison

Parameter TypeSyntaxBehavior
Requiredname: stringMust always be provided
Optionalname?: stringCan be skipped — becomes undefined
Defaultname: string = "Guest"Uses default when not provided
Rest...items: number[]Collects all extra arguments into array

Practical Example

// Exam result calculator
const calculateGrade = (
    studentName: string,
    marks: number,
    passMark: number = 40
): string => {
    if (marks >= 90) return studentName + " — Grade: A+";
    if (marks >= 75) return studentName + " — Grade: A";
    if (marks >= 60) return studentName + " — Grade: B";
    if (marks >= passMark) return studentName + " — Grade: C";
    return studentName + " — Failed";
};

console.log(calculateGrade("Divya", 92));
// Output: Divya — Grade: A+

console.log(calculateGrade("Nikhil", 55));
// Output: Nikhil — Grade: C

console.log(calculateGrade("Prerna", 30, 35));
// Output: Prerna — Failed

Leave a Comment