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.

An optional parameter in TypeScript is a function, method, or constructor parameter that is not strictly required during invocation. By appending a question mark (?) to the parameter identifier in the signature, the TypeScript compiler permits the caller to omit the argument, implicitly passing undefined in its place.
function functionName(requiredParam: Type, optionalParam?: Type): ReturnType {
    // Implementation
}

Type System Behavior

When a parameter is marked as optional, TypeScript automatically unions its declared type with undefined. Assuming --strictNullChecks is enabled in the tsconfig.json, a parameter declared as param?: string is evaluated by the type checker as string | undefined. Consequently, the compiler enforces type narrowing within the function body, requiring you to handle the undefined state before invoking methods specific to the declared type.
function parseInput(data: string, encoding?: string): void {
    // 'encoding' is typed as 'string | undefined'
    
    // Compiler Error: Object is possibly 'undefined'
    // let len = encoding.length; 
    
    if (encoding !== undefined) {
        // Type narrowed to 'string'
        let len = encoding.length; 
    }
}

parseInput("payload");           // Valid: encoding is omitted
parseInput("payload", "utf-8");  // Valid: encoding is provided

Structural Constraints

TypeScript enforces strict positional rules for optional parameters. All optional parameters must appear after all required parameters in the parameter list. A required parameter cannot follow an optional parameter.
// Valid: Optional parameter follows required parameter
function validSignature(a: number, b?: string): void {}

// Invalid: Required parameter follows optional parameter
// Compiler Error: A required parameter cannot follow an optional parameter.
function invalidSignature(a?: number, b: string): void {}

Interaction with Default Parameters

Parameters assigned a default value via an initializer (=) are inherently optional to the caller. However, you cannot combine the optional modifier (?) with a default initializer.
// Valid: Implicitly optional due to default initializer
function withDefault(a: number, b: string = "default"): void {}

// Invalid: Parameter cannot have question mark and initializer
// Compiler Error: Parameter cannot have question mark and initializer.
function conflictingSyntax(a: number, b?: string = "default"): void {}
Master TypeScript with Deep Grasping Methodology!Learn More