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

Sometimes, we want to pass optional parameters while omitting some other optional parameters with TypeScript.

In this article, we’ll look at how to pass optional parameters while omitting some other optional parameters with TypeScript.

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

To pass optional parameters while omitting some other optional parameters with TypeScript, we can add ? after the optional parameter mames.

For instance, we write

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);

to make the title and autoHideAfter parameters optional in the error method in the INotificationService.

Likewise, we add ? to the parameter names in the error method in the X class to make those fields optional.

Conclusion

To pass optional parameters while omitting some other optional parameters with TypeScript, we can add ? after the optional parameter mames.