Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 445
g.pickardou Avatar asked Jun 09 '15 14:06

g.pickardou


People also ask

How do you pass optional parameters?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

How can I pass optional or keyword parameters from one function to another?

Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. Without using keyword arguments. By using keyword arguments.

How do you pass optional parameters in TypeScript?

In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...

How do you pass optional parameters in react?

To add in an optional path parameter in React Router, you just need to add a ? to the end of the parameter to signify that it is optional. And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.


2 Answers

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.

like image 70
Thomas Avatar answered Sep 20 '22 19:09

Thomas


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}); 
like image 39
Brocco Avatar answered Sep 19 '22 19:09

Brocco