首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在传递可选参数的同时省略其他一些可选参数?

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

Stack Overflow用户
提问于 2015-06-09 22:09:10
回答 12查看 375K关注 0票数 390

给出以下签名:

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

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

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2015-06-09 22:20:02

按照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

票数 414
EN

Stack Overflow用户

发布于 2015-06-09 22:18:42

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

但是为了解决这个问题,你可以把你的params改成一个接口:

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

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

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

Stack Overflow用户

发布于 2018-10-05 22:46:04

另一种方法是:

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

因此,当您想要省略title参数时,只需像这样发送数据:

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

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

票数 42
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30734509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档