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

问题描述 投票:194回答:9

鉴于以下签名:

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

如何调用函数error()不指定title参数,但将autoHideAfter设置为1000

typescript
9个回答
236
投票

documentation中所述,使用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


56
投票

不幸的是,在TypeScript中没有这样的东西(更多细节在这里:https://github.com/Microsoft/TypeScript/issues/467

但是为了解决这个问题,你可以将你的参数改为接口:

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

export interface INotificationService {
  error(params: IErrorParams);
}

//then to call it:
error({message: 'msg', autoHideAfter: 42});

33
投票

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

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

在上面:

  • name是必需的
  • country是必需的,并且具有默认值
  • address是可选的
  • hobbies是一系列可选参数

10
投票

另一种方法是:

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

因此,当您想省略title参数时,只需发送如下数据:

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

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


9
投票

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

它最终有点像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:');

5
投票

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

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

现在所有这些都可行:

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

...而errorINotificationService方法将有以下选择:

Playground


1
投票

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

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

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

0
投票

您可以在没有界面的情况下执

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

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


0
投票

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

这对我有用。

错误('这是',null,1000)

© www.soinside.com 2019 - 2024. All rights reserved.