Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A function in TypeScript is a fundamental execution block that extends standard JavaScript functions by introducing static type annotations for parameters, return values, and execution context. This enforces a strict contract between the caller and the function implementation, allowing the TypeScript compiler to validate inputs and outputs at compile time.

Basic Typing

TypeScript allows you to explicitly define the types of arguments a function accepts and the type of data it returns. If a return type is omitted, TypeScript will attempt to infer it based on the return statements.
function calculateArea(width: number, height: number): number {
    return width * height;
}

const divide = (a: number, b: number): number => a / b;

Function Types

You can define the signature of a function as a standalone type using a type alias or an interface. This is useful for typing callbacks or enforcing a specific signature on variable declarations.
type StringTransformer = (input: string) => string;

const toUpperCase: StringTransformer = (text) => text.toUpperCase();

Optional and Default Parameters

By default, TypeScript assumes all defined parameters are required. You can mark a parameter as optional using the ? postfix, which implicitly adds undefined to its type. Alternatively, you can provide a default value, which makes the parameter optional and infers its type from the default assignment.
// Optional parameter
function buildName(firstName: string, lastName?: string): string {
    return lastName ? `${firstName} ${lastName}` : firstName;
}

// Default parameter
function increment(value: number, step: number = 1): number {
    return value + step;
}

Rest Parameters

When a function needs to accept a variable number of arguments, you use rest parameters. In TypeScript, rest parameters can be typed as an array for an indefinite number of arguments of a specific type, or as a tuple type to enforce a specific sequence and known count of arguments.
// Array rest parameter
function concatenateStrings(separator: string, ...strings: string[]): string {
    return strings.join(separator);
}

// Tuple rest parameter
function setCoordinates(...args: [number, number, string]): void {
    const [x, y, label] = args;
}

Generic Functions

Generic functions utilize type parameters to handle multiple types while preserving strict type identity between inputs and outputs. Type parameters are declared in angle brackets (<T>) immediately preceding the function signature. When returning intersection types generated via object spread, a type assertion is required because the compiler evaluates the spread as a plain object rather than the specific generic intersection.
// Single type parameter
function identity<T>(arg: T): T {
    return arg;
}

// Multiple type parameters with constraints and type assertion
function merge<T extends object, U extends object>(target: T, source: U): T & U {
    return { ...target, ...source } as T & U;
}

Function Overloading

TypeScript supports function overloading, allowing you to define multiple call signatures for a single function. The compiler resolves the correct signature based on the arguments provided. The overload signatures are declared first, followed by a single implementation signature that must be compatible with all preceding overloads.
// Overload signatures
function parseInput(input: string): string[];
function parseInput(input: number): number[];

// Implementation signature
function parseInput(input: string | number): string[] | number[] {
    if (typeof input === "string") {
        return input.split("");
    }
    return [input];
}

void and never Return Types

TypeScript introduces specific types for functions that do not return standard values:
  • void: Indicates that a function completes execution but does not return a value (or explicitly returns undefined).
  • never: Indicates that a function will never successfully complete execution, typically because it throws an error or contains an infinite loop.
function logWarning(message: string): void {
    console.warn(message);
}

function terminateProcess(reason: string): never {
    throw new Error(`Process terminated: ${reason}`);
}

this Typing

In TypeScript, you can explicitly type the this context of a function to prevent runtime errors caused by unbound execution contexts. The this parameter is a pseudo-parameter that must appear first in the parameter list and is erased during compilation.
interface User {
    name: string;
    greet(this: User): void;
}

const user: User = {
    name: "Alice",
    greet(this: User) {
        console.log(`Hello, ${this.name}`);
    }
};
Master TypeScript with Deep Grasping Methodology!Learn More