</>
Skip to content
TypeScript lessons (9/31)

TypeScript — Functions

Function types

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

// Arrow function
const multiply = (a: number, b: number): number => a * b;

// Function type
type MathOp = (a: number, b: number) => number;
const subtract: MathOp = (a, b) => a - b;

Optional and default parameters

// Optional parameter
function greet(name: string, greeting?: string): string {
    return `${greeting ?? "Hello"}, ${name}!`;
}

// Default parameter
function power(base: number, exponent: number = 2): number {
    return base ** exponent;
}

console.log(greet("Alice"));          // Hello, Alice!
console.log(greet("Alice", "Hi"));   // Hi, Alice!
console.log(power(3));                // 9
console.log(power(3, 3));             // 27

Rest parameters

function sum(...numbers: number[]): number {
    return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3));       // 6
console.log(sum(1, 2, 3, 4, 5)); // 15

Function overloads

// Overload signatures
function format(value: string): string;
function format(value: number): string;
function format(value: Date): string;

// Implementation
function format(value: string | number | Date): string {
    if (typeof value === "string") return value.toUpperCase();
    if (typeof value === "number") return value.toFixed(2);
    return value.toLocaleDateString();
}

console.log(format("hello"));      // HELLO
console.log(format(3.14159));      // 3.14
console.log(format(new Date()));   // 8/23/2026

Generic functions

// Generic function
function identity<T>(value: T): T {
    return value;
}

console.log(identity<string>("hello")); // hello
console.log(identity<number>(42));       // 42

// Type inference
const result = identity("hello"); // inferred as string

// Multiple type parameters
function pair<T, U>(first: T, second: U): [T, U] {
    return [first, second];
}

const p = pair("Alice", 30); // [string, number]

// Generic constraint
function getLength<T extends { length: number }>(value: T): number {
    return value.length;
}

console.log(getLength("hello"));    // 5
console.log(getLength([1, 2, 3]));  // 3

Higher-order functions

// Function that takes a function
function applyTwice(fn: (x: number) => number, value: number): number {
    return fn(fn(value));
}

const double = (x: number) => x * 2;
console.log(applyTwice(double, 3)); // 12

// Function that returns a function
function createMultiplier(factor: number) {
    return (value: number) => value * factor;
}

const triple = createMultiplier(3);
console.log(triple(5)); // 15

Callback types

type Callback = (error: Error | null, data?: string) => void;

function fetchData(url: string, callback: Callback): void {
    // Simulate async work
    setTimeout(() => {
        callback(null, `Data from ${url}`);
    }, 100);
}

fetchData("https://api.example.com", (err, data) => {
    if (err) {
        console.error(err.message);
    } else {
        console.log(data);
    }
});

Async functions

async function fetchUser(id: number): Promise<{ name: string; age: number }> {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 100));
    return { name: "Alice", age: 30 };
}

async function main() {
    const user = await fetchUser(1);
    console.log(user.name);
}

// Async arrow function
const getData = async (): Promise<string> => {
    return "data";
};

// Promise types
function delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Type predicates

function isString(value: unknown): value is string {
    return typeof value === "string";
}

function process(value: string | number) {
    if (isString(value)) {
        // value is string here
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

Mini Practice

Write TypeScript code that:

  1. Creates a generic function that reverses an array
  2. Uses function overloads for a format function
  3. Creates a higher-order function that filters arrays
  4. Writes an async function with proper return types

Up Next

In the next lesson, you'll learn about Interfaces — defining object shapes.

Related Topics

Frequently Asked Questions about Functions

What is Functions in TypeScript?

Functions is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Functions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.

Why is Functions important in TypeScript?

Functions is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.