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 building block that encapsulates reusable logic, distinguished from standard JavaScript by the addition of static typing for parameters, return values, and execution context (this). TypeScript enforces strict type checking during compilation to ensure that function invocations strictly adhere to their defined structural signatures.

Parameter and Return Type Annotations

TypeScript allows explicit type declarations for both the arguments a function accepts and the value it returns. If a return type is omitted, TypeScript will attempt to infer it based on the return statements.
// Named function with explicit parameter and return types
function calculateArea(width: number, height: number): number {
    return width * height;
}

// Arrow function with explicit types
const concatenate = (str1: string, str2: string): string => `${str1}${str2}`;

Function Types

Function signatures can be abstracted into standalone types or interfaces. This enables contextual typing, where TypeScript infers the types of the parameters and return value based on the assigned type alias.
// Defining a function type alias
type StringTransformer = (input: string) => string;

// The compiler infers 'text' is a string and the return is a string
const toUpperCase: StringTransformer = (text) => text.toUpperCase();

Optional and Default Parameters

By default, TypeScript assumes all parameters defined in a function signature are required.
  • Optional Parameters: Denoted by a ? postfix on the parameter identifier. They must appear after all required parameters.
  • Default Parameters: Assigned using the = operator. TypeScript infers the parameter type from the default value if no explicit type annotation is provided.
// 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

To represent an unbounded number of arguments, TypeScript uses rest parameters. The rest parameter must be the final parameter in the signature and is typed as an array.
function sumAll(initialValue: number, ...additionalValues: number[]): number {
    return additionalValues.reduce((acc, val) => acc + val, initialValue);
}

Function Overloading

TypeScript supports function overloading, allowing multiple type signatures for a single function implementation. The compiler resolves the call against the list of overload signatures, evaluating them from top to bottom. The actual implementation signature must be broad enough to encompass all overload signatures and is not directly callable itself.
// 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];
}

Special Return Types: void and never

TypeScript introduces specific types to represent the absence of a return value or the impossibility of returning.
  • void: Indicates that a function does not return a value (or explicitly returns undefined).
  • never: Indicates that a function never successfully completes execution, typically because it throws an exception or enters an infinite loop.
function logEvent(event: string): void {
    console.log(`Event: ${event}`);
}

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

Typing the this Context

In JavaScript, the value of this is determined by how a function is called. TypeScript allows you to explicitly type the this context by declaring it as a pseudo-parameter. It must be the first parameter in the function signature and is stripped out during compilation.
interface Handler {
    elementId: string;
    onClick(this: Handler, event: Event): void;
}

const myHandler: Handler = {
    elementId: "btn-submit",
    onClick(this: Handler, event: Event) {
        console.log(`Clicked ${this.elementId}`);
    }
};
Master TypeScript with Deep Grasping Methodology!Learn More