How to pass optional parameters while omitting some other optional parameters?

g.pickardou picture g.pickardou · Jun 9, 2015 · Viewed 281.8k times · Source

Given the following signature:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
}

How can I call the function error() not specifying the title parameter, but setting autoHideAfter to say 1000?

Answer

Thomas picture Thomas · Jun 9, 2015

As specified in the documentation, use undefined:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter? : number);
}

class X {
    error(message: string, title?: string, autoHideAfter?: number) {
        console.log(message, title, autoHideAfter);
    }
}

new X().error("hi there", undefined, 1000);

Playground link.