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

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


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.


Unfortunately there is nothing like this in TypeScript (more details here: https://github.com/Microsoft/TypeScript/issues/467)

But to get around this you can change your params to be an interface:

export interface IErrorParams {  message: string;  title?: string;  autoHideAfter?: number;}export interface INotificationService {  error(params: IErrorParams);}//then to call it:error({message: 'msg', autoHideAfter: 42});


you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {    // ...}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params