typescript 如何在省略一些其他可选参数的同时传递可选参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30734509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:41:00  来源:igfitidea点击:

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

typescript

提问by g.pickardou

Given the following signature:

鉴于以下签名:

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

How can I call the function error()notspecifying the titleparameter, but setting autoHideAfterto say 1000?

如何调用函数error()而不指定title参数,而是设置autoHideAfter1000

回答by Thomas

As specified in the documentation, use undefined:

按照文档中的规定,使用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.

游乐场链接

回答by Brocco

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

不幸的是,TypeScript 中没有这样的东西(更多细节在这里: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});

回答by Hasan A Yousef

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

您可以使用可选变量 by?或者如果您有多个可选变量 by ...,例如:

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

In the above:

在上面:

  • nameis required
  • countryis required and has a default value
  • addressis optional
  • hobbiesis an array of optional params
  • name是必须的
  • country是必需的并且有一个默认值
  • address是可选的
  • hobbies是可选参数的数组

回答by Gabriel Castillo Prada

Another approach is:

另一种方法是:

error(message: string, options?: {title?: string, autoHideAfter?: number});

So when you want to omit the title parameter, just send the data like that:

所以当你想省略 title 参数时,只需发送这样的数据:

error('the message', { autoHideAfter: 1 })

I'd rather this options because allows me to add more parameter without having to send the others.

我更喜欢这个选项,因为允许我添加更多参数而不必发送其他参数。

回答by Monkpit

This is almost the same as @Brocco 's answer, but with a slight twist: only pass optional parameters in an object.(And also make params object optional).

这与@Brocco 的答案几乎相同,但略有不同:仅在对象中传递可选参数。(并且还使 params 对象可选)。

It ends up being kind of like Python's **kwargs, but not exactly.

它最终有点像 Python 的 **kwargs,但不完全是这样。

export interface IErrorParams {
  title?: string;
  autoHideAfter?: number;
}

export interface INotificationService {
  // make params optional so you don't have to pass in an empty object
  // in the case that you don't want any extra params
  error(message: string, params?: IErrorParams);
}

// all of these will work as expected
error('A message with some params but not others:', {autoHideAfter: 42});
error('Another message with some params but not others:', {title: 'StackOverflow'});
error('A message with all params:', {title: 'StackOverflow', autoHideAfter: 42});
error('A message with all params, in a different order:', {autoHideAfter: 42, title: 'StackOverflow'});
error('A message with no params at all:');

回答by David Sherret

You can specify multiple method signatures on the interface then have multiple method overloads on the class method:

您可以在接口上指定多个方法签名,然后在类方法上有多个方法重载:

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

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

Now all these will work:

现在所有这些都将起作用:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...and the errormethod of INotificationServicewill have the following options:

...和error方法INotificationService将有以下选项:

Overload intellisense

过载智能感知

Playground

操场

回答by malbarmavi

You can create a helper method that accept a one object parameter base on error arguments

您可以创建一个辅助方法,该方法接受基于错误参数的单对象参数

 error(message: string, title?: string, autoHideAfter?: number){}

 getError(args: { message: string, title?: string, autoHideAfter?: number }) {
    return error(args.message, args.title, args.autoHideAfter);
 }

回答by numpsi

You could try to set title to null.

您可以尝试将 title 设置为 null。

This worked for me.

这对我有用。

error('This is the ',null,1000)

回答by Rick

You can do this without an interface.

您可以在没有界面的情况下执行此操作。

class myClass{
  public error(message: string, title?: string, autoHideAfter? : number){
    //....
  }
}

use the ?operator as an optional parameter.

使用?运算符作为可选参数。