Typescript 如何在忽略其他可选参数的同时传递可选参数?

Typescript 如何在忽略其他可选参数的同时传递可选参数?,typescript,Typescript,签字如下: export interface INotificationService { error(message: string, title?: string, autoHideAfter?: number); } 如何调用函数error()不指定title参数,而是将autoHideAfter设置为1000?不幸的是,TypeScript中没有类似的功能(更多详细信息如下:) 但要解决此问题,您可以将参数更改为接口: export interface IErrorParams

签字如下:

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

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

不幸的是,TypeScript中没有类似的功能(更多详细信息如下:)

但要解决此问题,您可以将参数更改为接口:

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

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

//then to call it:
error({message: 'msg', autoHideAfter: 42});
如中所述,使用
未定义的

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

.

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

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
    }
}
…并且
INotificationService
错误
方法将具有以下选项:


这与@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:');

您可以在没有接口的情况下执行此操作

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

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

您可以通过
使用可选变量,或者如果您通过
拥有多个可选变量,…
,例如:

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

  • 名称
    是必需的
  • 国家/地区
    为必填项,并具有默认值
  • 地址
    是可选的
  • 嗜好
    是一个可选参数数组

您可以尝试将title设置为null

这对我有用

error('This is the ',null,1000)
另一种方法是:

error(message: string, options?: {title?: string, autoHideAfter?: number});
因此,如果要省略title参数,只需发送如下数据:

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

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

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

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

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

在TS中,您还可以将参数设置为对象,并将对象的值设置为可选值,这样您就不必定义每个参数,只需定义您想要使用的参数即可

调用公共函数(对象:{status?:number,error?:string,message?:string}){ if(obj.message){console.log(obj.message)} }
this.functionBeingCalled({message:'Error Detected'})
我建议不要这样做,而是传入一个对象并将这些参数作为该对象的属性。。。它的工作量要小得多,代码的可读性也更高。这不是一个好主意。如果我有三个字符串参数,但只想省略其中一个参数,该怎么办?这不起作用,因为所有三个覆盖都具有相同的签名,但这不允许您以任何方式指定
消息
自动隐藏后
您没有回答问题或没有阅读它。他想知道如何使用多个可选参数调用方法,如果他只想输入第二个可选参数,则不必指定第一个可选参数。@BBi7我想您误解了文档。函数定义中添加了
,但问题是实际调用函数。嗨@Thomas我完全理解文档,知道您必须添加?在函数定义中的参数之后。但是,关于使用可选参数调用函数,如果不适用,我将假定传递未定义的参数。我通常会设法将可选参数设置为结束参数,这样我就不能通过vs.undefined了。但显然,如果你有很多,那么你需要通过未定义或任何非真实的。我不确定我最初发帖时指的是什么。这意味着我不知道它是否被编辑过,但我现在看到的是正确的。@BBi7最近没有编辑过。好的,没关系:)(请注意,您实际上必须传递
undefined
,以获得与完全忽略参数相同的行为。仅仅“任何非真实的”都不起作用,因为TypeScript与
void 0
相比,后者是编写
undefined
更安全的方式)这会起作用,因为如果在向函数参数发送null时函数参数具有默认值,则该函数参数将不会设置为其默认值。是否应将其键入数组?此答案中包含有用的信息,但它没有回答问题。在我看来,问题是如何绕过/跳过几个可选参数,而只设置特定的参数。country不是必需的,它是一个可选参数,默认值为“CA”,而不是未定义的。如果它是必需的,那么提供默认值有什么意义呢?您如何将默认值传递给
title
?@DanDascalescu
…,选项?:{title?:string}={title:“我的默认值”},
您能告诉我,我能这样调用error方法吗,error({message:'test}),我想,我们不能,所以error({message:'test',autoHideAFter:undefined}),但我期望的是错误(message),如果我没有传递其他参数,它应该从默认参数中获取值。
 error(message: string, title?: string, autoHideAfter?: number){}

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