SyntaxStudy
Sign Up
TypeScript Beginner 10 min read

TypeScript Functions

TypeScript allows you to type function parameters, return values, and even function signatures themselves. This makes it clear what a function expects and returns, reducing bugs significantly.

Example
// Typed parameters and return type
function add(a: number, b: number): number {
    return a + b;
}

// Optional and default parameters
function greet(name: string, greeting: string = 'Hello'): string {
    return `${greeting}, ${name}!`;
}

// Rest parameters
function sum(...nums: number[]): number {
    return nums.reduce((acc, n) => acc + n, 0);
}

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

// Void return (no return value)
function logMessage(msg: string): void {
    console.log(`[LOG] ${msg}`);
}

// Overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
    return typeof value === 'number' ? value.toFixed(2) : value.trim();
}

// Generic function
function first<T>(arr: T[]): T | null {
    return arr.length > 0 ? arr[0] : null;
}