TS TypeScript

TypeScript: Functions with Types

What you will learn

How to type function parameters, return values, optional parameters, and default values.

Parameter and return types

function greet(name: string): string {
    return `Hello, ${name}!`;
}

function logMessage(msg: string): void {
    console.log(msg);
    // no return statement needed
}

The return type goes after the parameters with a colon. void means the function returns nothing usefull -- no return value expected.

Optional parameters (?)

function greet(name: string, greeting?: string): string {
    const g = greeting ?? 'Hello';
    return `${g}, ${name}!`;
}

greet('Alice');           // Hello, Alice!
greet('Alice', 'Hi');     // Hi, Alice!

Optional parameters must come after required parameters.

Default parameters

function multiply(a: number, b: number = 2): number {
    return a * b;
}

multiply(5);    // 10
multiply(5, 3); // 15

Arrow functions with types

const double = (n: number): number => n * 2;

// When passing as a callback, the type is often inferred:
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2);  // n inferred as number

Common mistakes

  • Forgetting the return type annotation on complex functions -- TS infers it, but explicit types act as documentation and catch errors earlier
  • Confusing optional ? with default = value -- ? means the parameter can be undefined; = value provides a fallback

Quick check below!