SyntaxStudy
Sign Up
TypeScript Function Types, Overloads, and Optional Parameters
TypeScript Beginner 1 min read

Function Types, Overloads, and Optional Parameters

In TypeScript, functions are first-class values and have their own types. A function type describes the parameter types and the return type of a function. You can write function types inline, assign them to type aliases, or describe them with call signatures in interfaces. TypeScript infers return types from function bodies, but explicitly annotating them is good practice for public APIs. Function overloading lets you define multiple call signatures for a single function. You write several overload signatures followed by an implementation signature that must be compatible with all of them. The implementation is not directly callable from outside — callers only see the overload signatures. This allows one function to accept different argument patterns and return different types depending on how it is called. Optional parameters are declared with ? after the parameter name. They must come after all required parameters. Default parameter values serve a similar purpose but also provide the default when the caller passes undefined. Rest parameters collect any number of trailing arguments into a typed array. These features together cover the full range of function call patterns found in JavaScript.
Example
// Basic function type annotation
function add(a: number, b: number): number {
    return a + b;
}

// Function type alias
type BinaryOp = (a: number, b: number) => number;
const multiply: BinaryOp = (a, b) => a * b;

// Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string {
    return `${greeting}, ${name}!`;
}
console.log(greet("Alice"));           // Hello, Alice!
console.log(greet("Bob", "Hi"));       // Hi, Bob!

// Rest parameters
function sum(...numbers: number[]): number {
    return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

// Function overloads
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
    if (typeof value === "string") return value.trim();
    return value.toFixed(decimals ?? 2);
}

console.log(format("  hello  "));   // "hello"
console.log(format(3.14159, 2));    // "3.14"

// void vs never return types
function logInfo(msg: string): void {
    console.log("[INFO]", msg);
}

function panic(msg: string): never {
    throw new Error(msg);
}