简体   繁体   English

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

[英]How to pass optional parameters while omitting some other optional parameters?

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 ?如何调用 function error()而不指定title参数,但将autoHideAfter设置为1000

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 . 游乐场链接

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

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 name为必填项
  • country is required and has a default value country为必填项,并具有默认值
  • address is optional address是可选的
  • hobbies is an array of optional params hobbies是可选参数的数组

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. 我宁愿使用此选项,因为它允许我添加更多参数而不必发送其他参数。

This is almost the same as @Brocco 's answer, but with a slight twist: only pass optional parameters in an object. 这几乎与@Brocco的答案相同,但略有不同: 仅在对象中传递可选参数。 (And also make params object optional). (并且还将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:');

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 error method of INotificationService will have the following options: ...并且INotificationServiceerror方法将具有以下选项:

过载智能

Playground 操场

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

In TS you could also make your parameters into an Object and make the value of the object optional, that way you don't have to define every parameters, just the one you want to use.在 TS 中,您还可以将参数设置为 Object 并使对象的值可选,这样您就不必定义每个参数,只需定义您想要使用的参数即可。

 public functionBeingCalled(obj: {status?: number, error?: string, message?: string}) { if(obj.message) { console.log(obj.message) } } this.functionBeingCalled({message: 'Error Detected'})

You can do this without an interface. 您可以在没有界面的情况下执行此操作。

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

use the ? 使用? operator as an optional parameter. 运算符作为可选参数。

You could try to set title to null. 您可以尝试将title设置为null。

This worked for me. 这对我有用。

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

In such cases you can use "undefined" value for those optional params which you do not want to overwrite在这种情况下,您可以对那些不想覆盖的可选参数使用“未定义”值

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

You can call error method like您可以调用错误方法,如

error("it works", undefined, 20);

Be careful null doesn't work here.小心null在这里不起作用。

https://www.typescriptlang.org/docs/handbook/functions.html https://www.typescriptlang.org/docs/handbook/functions.html

In JavaScript, every parameter is optional, and users may leave them off as they see fit.在 JavaScript 中,每个参数都是可选的,用户可以根据需要将其关闭。 When they do, their value is undefined.当他们这样做时,他们的价值是不确定的。 We can get this functionality in TypeScript by adding a?我们可以通过添加一个? to the end of parameters we want to be optional.到我们希望是可选的参数的末尾。 For example, let's say we want the last name parameter from above to be optional:例如,假设我们希望上面的姓氏参数是可选的:

function buildName(firstName: string, lastName?: string) {
  if (lastName) return firstName + " " + lastName;
  else return firstName;
}
 
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
Expected 1-2 arguments, but got 3.
let result3 = buildName("Bob", "Adams"); // ah, just right

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM